I thought function xrange would give me a list of integers, but I got a string instead:

x = "xrange(1, 5)"
print x           # xrange(1, 5)
x = xrange(1, 5)
print x           # xrange(1, 5) same result as string above!?

I thought function xrange would give me a list of integers, but I got a string instead:

x = "xrange(1, 5)"
print x           # xrange(1, 5)
x = xrange(1, 5)
print x           # xrange(1, 5) same result as string above!?

if you look at the xrange() docs. it says "returns an ``xrange object'' instead of a list"
if you want to use xrange(). use a for loop

for i in xrange(1,5):.....

I took the liberty to use x and y so you can see the key:value difference in the Python internal globals dictionary ...

x = "xrange(1, 5)"
print x           # xrange(1, 5)
print type(x)     # <type 'str'>  string named xrange
print list(x)     # ['x', 'r', 'a', 'n', 'g', 'e', '(', '1', ',', ' ', '5', ')']
print x[1]        # r
print x[2]        # a

y = xrange(1, 5)
print y           # xrange(1, 5) same result as string above!?
print type(y)     # <type 'xrange'> object named xrange
print list(y)     # [1, 2, 3, 4]
print y[1]        # 2
print y[2]        # 3

print globals()   # {... , 'x': 'xrange(1, 5)', 'y': xrange(1, 5), ...}

print xrange.__doc__
"""
Like range(), but instead of returning a list, returns an object that
generates the numbers in the range on demand.  For looping, this is
slightly faster than range() and more memory efficient.
"""

Welcome to our Python forum sneekula. We are small in number, but quite friendly, and try to make you feel at home!

Okay, I get it. On the display the string and the xrange object came up looking alike. That confused me! Thanks for the insight on using the xrange() function. It's all new to me and I will keep asking "not so smart questions" a lot!

This question has already been answered. Start a new discussion instead.