A list is a data structure that holds a sequence of values. An iterator is an object that provides an interface to retrieve values one at a time, via the next
function.
An iterable object is one that provides a __iter__
method, which is invoked when you pass an iterable to the iter
function. You don't often need to do this explicitly; a for
loop, for example, does it implicitly. A loop like
for x in [1,2,3]:
print x
automatically invokes the list
's __iter__
method. You can do so explicitly with
for x in iter([1,2,3]):
print x
or even more explicitly with
for x in [1,2,3].__iter__():
print x
One way to see the difference is to create two iterators from a single list.
l = [1, 2, 3, 4, 5]
i1 = iter(l)
i2 = iter(l)
print next(i1) # 1
print next(i1) # 2
print next(i2) # 1 again; i2 is separate from i1
print l # [1, 2, 3, 4, 5]; l is unaffected by i1 or i2