Applying iter() to an iterable creates an iterator
Iterator
Produces next value with next()
An iterable is an object that can return an iterator, while an iterator is an object that keeps state and produces the next value when you call next() on it.
Iterating over iterables (list)
# Create a list of strings: flashflash = ['jay garrick','barry allen','wally west','bart allen']# Print each list item in flash using a for loopfor person in flash:print (person)# Create an iterator for flash: superherosuperhero=iter(flash)# Print each item from the iteratorprint(next(superhero))print(next(superhero))print(next(superhero))print(next(superhero))
Iterating over dictionaries
pythonistas ={'hugo':'bowne-anderson','francis':'castro'}for key, value in pythonistas.items():print(key, value)# francis castro# hugo bowne-anderson
Iterating over file connections
file =open('file.txt')it =iter(file)print(next(it))#This is the first line.print(next(it))#This is the second line.
Iterating over iterables (range)
Not all iterables are actual lists. You can use range() in a for loop as if it's a list to be iterated over:
for i in range(5):
print(i)
Recall that range() doesn't actually create the list; instead, it creates a range object with an iterator that produces the values until it reaches the limit (in the example, until the value 4).
# Create an iterator for range(10 ** 100): googolgoogol =iter(range(10**100))# Print the first 5 values from googolprint(next(googol))print(next(googol))
Iterators as function arguments
There are also functions that take iterators and iterables as arguments. For example, the list() and sum() functions return a list and the sum of elements, respectively.
enumerate()
enumerate() returns an enumerate object that produces a sequence of tuples, and each of the tuples is an index-value pair.
Then, we can use list to turn this enumerate object into a list of tuples and print to see what it contains
enumerate() and unpack
avengers = ['hawkeye','iron man','thor','quicksilver'] for index, value inenumerate(avengers):#enumerate(avengers, start=10)print(index, value)#0 hawkeye#1 iron man#2 thor#3 quicksilver
zip()
zip() takes any number of iterables and returns a zip object that is an iterator of tuples.