Posts: 4
Threads: 2
Joined: Apr 2017
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
Posts: 8,156
Threads: 160
Joined: Sep 2016
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]
Posts: 12,024
Threads: 484
Joined: Sep 2016
looks like a Multiple Choice question from an exam.
Posts: 4
Threads: 2
Joined: Apr 2017
yes,but according to you what shoukd be correct option,i am very sure that i am right but it is coming wrong
Posts: 8,156
Threads: 160
Joined: Sep 2016
did you see in my example the list that range(4) produce?
Posts: 7,313
Threads: 123
Joined: Sep 2016
# Python 2
>>> range(4)
[0, 1, 2, 3] In Python 3 use list()
>>> list(range(4))
[0, 1, 2, 3]
Posts: 4
Threads: 2
Joined: Apr 2017
thanks Buran and snippsat,but i am not getting this as a correct choice
Posts: 8,156
Threads: 160
Joined: Sep 2016
calm down and read the 4 options again, keeping in mind what I and snippsat are telling you :-)
Posts: 2,953
Threads: 48
Joined: Sep 2016
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
>>>
Posts: 3,458
Threads: 101
Joined: Sep 2016
>>> 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.
|