Introduction to iterators

Python Toolbox

Hugo Bowne-Anderson

Data Scientist at DataCamp

Iterating with a for loop

  • We can iterate over a list using a for loop
employees = ['Nick', 'Lore', 'Hugo']

for employee in employees: print(employee)
Nick
Lore
Hugo
Python Toolbox

Iterating with a for loop

  • We can iterate over a string using a for loop
for letter in 'DataCamp':
    print(letter)
D
a
t
a
C
a
m
p
Python Toolbox

Iterating with a for loop

  • We can iterate over a range object using a for loop
for i in range(4):
    print(i)
0
1
2
3
Python Toolbox

Iterators vs. iterables

  • Iterable
    • Examples: lists, strings, dictionaries, file connections
    • An object with an associated iter() method
    • Applying iter() to an iterable creates an iterator
  • Iterator
    • Produces next value with next()
Python Toolbox

Iterating over iterables: next()

word = 'Da'
it = iter(word)

next(it)
'D'
next(it)
'a'
next(it)
StopIteration                   Traceback (most recent call last)
<ipython-input-11-2cdb14c0d4d6> in <module>()
-> 1 next(it)
StopIteration:
Python Toolbox

Iterating at once with *

word = 'Data'
it = iter(word)

print(*it)
D a t a
print(*it)
  • No more values to go through!
Python Toolbox

Iterating over dictionaries

pythonistas = {'hugo': 'bowne-anderson', 'francis': 'castro'}

for key, value in pythonistas.items(): print(key, value)
francis castro
hugo bowne-anderson
Python Toolbox

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.
Python Toolbox

Let's practice!

Python Toolbox

Preparing Video For Download...