Python Forum

Full Version: range and xrange
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In Python, which of the following descriptions about range() and xrange() is NOT true?

In Python 2, when it is needed to generate a quite large sequence of numbers, the performance of xrange() is better than that of range(), saving more memory.

In Python 2, range() returns a “list” object, while xrange() returns a generator.

In Python 2, range(4) returns a “list” object of [1,2,3,4].

In Python 3, only range() does not return the “list” object returned in Python 2.
according to me it should be option 4 but it is coming incorrect..
please help
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> range(4)
[0, 1, 2, 3]
looks like a Multiple Choice question from an exam.
yes,but according to you what shoukd be correct option,i am very sure that i am right but it is coming wrong
did you see in my example the list that range(4) produce?
# Python 2
>>> range(4)
[0, 1, 2, 3]
In Python 3 use list()
>>> list(range(4))
[0, 1, 2, 3]
thanks Buran and snippsat,but i am not getting this as a correct choice
calm down and read the 4 options again, keeping in mind what I and snippsat are telling you :-)
In Python 3 range() is an iterator.
That means that it will not generate all values at once and produce a lust for example but it returns one value per call.
What I mean:
>>> r = range(5)
>>> i = iter(r)
>>> r
range(0, 5)
>>> i
<range_iterator object at 0x7f52ed2cdcc0>
>>> next(i)
0
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
4
>>> next(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 
Looping over a range(5) is not looping over a list ( what it was in Python 2 range() ) but instead next() is called and 0 is produced the first time. Than next() is called again and is produced 1. It keeps the state so all is in order. Until all vallues are out and StopIteration is raised.

Here is the equivalent of a for loop as it is in above code:
>>> r = range(5)
>>> i = iter(r)
>>> while True:
...     try:
...         next(i)
...     except StopIteration:
...         break
... 
0
1
2
3
4
>>> 
>>> list(range(4))
[0, 1, 2, 3]
>>> list(range(1, 5))
[1, 2, 3, 4]
Python, along with most other languages, are zero-based, not 1-based.