a = range(1, 3)
a = iter(a)
list(a)
a = list(a)
a evaluates to [ ].
a = range(1, 3)
a = iter(a)
a = list(a)
a evaluates to [1, 2].
The first result is unexpected to me. What semantics are going on here?
The issue is not list() but iter() which as documented returns a single-use iterator. Once something has accessed the iterator's elements, the iterator is permanently empty. The more commonly used iterable type is (normally) reusable, and the two types shouldn't be confused.
Note that you don't need iter() in order to turn a range into a list, because list() takes an iterable as an argument:
>>> a = range(1, 3)
>>> list(a)
[1, 2]
>>> list(a)
[1, 2]
And it is only the iterator returned by iter() that is single-use:
>>> b = iter(a)
>>> list(b)
[1, 2]
>>> list(b)
[]
>>> list(a)
[1, 2]
Let's examine what happens:
>>> a = range(1, 3)
>>> a is iter(a)
False
as you can see, iter gives a new iterator object, which is not a itself
>>>> a = iter(a)
the name a now corresponds to the distinct iterator object iter gave us (just as if iter(a) had returned itself, e.g. as it happens with zip and with files)
>>> list(a)
[1, 2]
exhausts the iterator, therefore
>>> list(a)
[]
gives nothing as the iterator has been used (iterated on) already
Here are a few more experiments you can try to fully grasp what happens:
>>> a = range(1, 3)
>>> a
range(1, 3)
>>> type(a)
<class 'range'>
>>> b = iter(a)
>>> b
<range_iterator object at 0x7f331a6d96c0>
>>> type(b)
<class 'range_iterator'>
>>> a is b
False
>>> list(b)
[1, 2]
>>> list(b)
[]
>>> list(a)
[1, 2]
>>> list(a)
[1, 2]
>>> a
range(1, 3)
>>> next(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'range' object is not an iterator
>>> b=iter(a)
>>> next(b)
1
>>> next(b)
2
>>> next(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> z=zip(a,b)
>>> iter(z) is z
True
>>> with open('words.txt') as f:
... iter(f) is f
...
True
Note: on Python 2 quite a few functions return lists instead of iterators (e.g. zip)
a = iter(a)
list(a)
^^^^^^^
Means convert an iterator to a list, and don't save the output. However, a iterator can only produce the output once. After you read it it'll become empty.
And if you try next() here, you can also see what's happening:
>>> next(a)
1
>>> next(a)
2
>>> next(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
StopIteration
>>> list(a)
[]
From the document:
An object representing a stream of data. Repeated calls to the iterator’s
__next__()method (or passing it to the built-in functionnext()) return successive items in the stream.When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its
__next__()method just raise StopIteration again.
list() takes any iterable, not just generators, and 2) iter() returns a general iterator, not a generator iterator.
with open('foobar.txt') as f: f.read(), you cannot read it again unless you call f.seek(0).
Commented
Jan 11, 2016 at 23:13
read() to process the stream of data from a file-like object (which always returns bytes or strings) and next() to process the stream of elements from an iterator, which can return any type.
Creating a list from an iterator consumes the iterator. Simply spoken, its elements are created when needed and the content of the iterator is empty after you iterated over it. If you ever want another copy of an iterator, for example for creating a list, you can use itertools.tee.
>>> from itertools import tee
>>> it1, it2 = tee(range(1,3))
>>> lst = list(it1)
>>> lst
[1, 2]
>>> for x in it2:
... print(x)
...
1
2
>>> list(it2) # it2 is now exhausted
[]
list(thing) means iterate all the items from thing (as for item in thing would do), and save all of the items in a new list.
iter(thing) means get an "iterator" for thing; an iterator is basically a marker in a stream of data items remembering where you're up to, than can be used to get the next item from the stream (advancing the "marker" as a side effect). It explicitly does not have any way of resetting the marker back to the start to repeat the iteration; this is so that it can support iteration of things that inherently cannot be iterated multiple times.
Iterating all the items from thing (as for item in thing) gets an iterator for thing, and then uses the iterator to retrieve all of the items from the thing. So if you do this:
a = range(1, 3)
for x in a:
print x
for x in a:
print x
The for loop creates a new iterator for a (which starts with the marker at the start of the range), then pulls items from the iterator until it runs off the end of the range. The range object itself is untouched, so the second for loop can create a new iterator (starting at the start again) and iterate it again.
But here:
a = range(1, 3)
a = iter(a)
for x in a:
print x
for x in a:
print x
You're not letting the for loop create an iterator for the range, instead you're doing it explicitly, and only once. When the for loop goes to create an iterator from a the iterator it gets is just a itself (iter(i) when i is an iterator is always required to return i). So the for loop pulls items from a, advancing the marker each time, until the marker is "off the end" of the range object.
Then the second for loop makes an iterator from the iterator a, and again gets a itself. It then pulls items from that iterator until it runs out; which it can do zero times because a is already "off the end".
So it's actually nothing to do with your list calls directly, it's just how iterator objects that you get with iter behave. Ordinarily you don't use iter very much, because the things you use to iterate collections (for loops, list(), etc) already handle the creation of iterators for you. You would only use iter when you're doing something complicated involving partially consuming an iterator, and then consuming more items starting from where the first partial iteration left off.
iter() returns an iterator, and calling list() a second time on it returns an empty sequence.
>>> a = iter(range(1,3))
>>> list(a)
[1, 2]
>>> list(a)
[]
Docs about iterable:
When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values.
Docs about iterator:
A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.
listconsumes the iterable; why was that unexpected? How else would the elements get into the list? You can't consume the same iterable twice.