I am reading the book Think Python: How to think like a computer scientist, which says that in Python 3.x, dict([list of tuples]) returns an iterator instead of a list (as is the case in Python 2.7).
The book did not explain it any further, which has left me confused. In particular, I would like to know:
How are iterators and lists different, and
What is the advantage of returning an iterator over a list?
解决方案
First of all, your book is wrong (or you've misunderstood it):
>>> dict([(1, 2), (3, 4), (5, 6)])
{1: 2, 3: 4, 5: 6}
As you can see, dict([list of tuples]) returns a dictionary in both Python 2.x and 3.x.
The fundamental difference between a list and an iterator is that a list contains a number of objects in a specific order - so you can, for instance, pull one of them out from somewhere in the middle:
>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list[3]
'd'
... whereas an iterator yields a number of objects in a specific order, often creating them on the fly as requested:
>>> my_iter = iter(range(1000000000000))
>>> my_iter
>>> next(my_iter)
0
>>> next(my_iter)
1
>>> next(my_iter)
2
I'm using next() here for demonstration purposes; in real code it's more common to iterate over an iterator with a for loop:
for x in my_iter:
# do something with x
Notice the trade-off: a list of a trillion integers would use more memory than most machines have available, which makes the iterator much more efficient ... at the cost of not being able to ask for an object somewhere in the middle:
>>> my_iter[37104]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'range_iterator' object is not subscriptable