Introduction to Iterators
When you use a for loop to print out each element of a list, you're iterating over the list:
employees = ['Nick', 'Lore', 'Hugo']
for employee in employees:
print(employee)
You can also use a for loop to iterate over characters in a string:
for letter in 'DataCamp':
print(letter)
You can use a for loop to iterate over a sequence of numbers produced by a special range object as well:
for i in range(4):
print(i)
The reason that we can loop over such objects is that they are special objects called iterables. Lists, strings and range objects are all iterables, as are many other Python obkects, such as dictionaries and file connections.
The actual definition of an iterable is an object that has an associated iter() method. Once this iter() method is applied to an iterable, an iterator object is created. Under the hood, a for loop:
- Takes an iterable
- Creates the associated iterator object
- Iterates over the iterator object
An iterator is defined as an object that has an associated next() method that produces the consecutive values:
word = 'Da'
it = iter(word)
next(it)
You can also print all values of an iterator in one fell swoop using the star operator, referred to as the splat operator:
word = 'Da'
it = iter(word)
print(*it)
To iterate over the key-value pairs of a Python dictonary, we need to unpack them by applying the items() method to the dictionary:
pythonistas = {'hugo': 'bowne-anderson', 'francis': 'castro'}
for key, value in pythonistas.items():
print(key, value)
Here's an example to how to use iter() and next() methods with file connections:
file = open('file.txt')
it = iter(file)
# Prints line by line
print(next(it))
print(next(it))