Py Toolbox 4 Iterators
Py Toolbox 4 Iterators
iterators
P Y T H O N D ATA S C I E N C E TO O L B O X ( PA R T 2 )
Hugo Bowne-Anderson
Data Scientist at DataCamp
Iterating with a for loop
We can iterate over a list using a for loop
Nick
Lore
Hugo
D
a
t
a
C
a
m
p
for i in range(4):
print(i)
0
1
2
3
Iterable
Examples: lists, strings, dictionaries, le connections
Iterator
Produces next value with next()
'D'
next(it)
'a'
next(it)
print(*it)
D a t a
print(*it)
francis castro
hugo bowne-anderson
print(next(it))
print(next(it))
Hugo Bowne-Anderson
Data Scientist at DataCamp
Using enumerate()
avengers = ['hawkeye', 'iron man', 'thor', 'quicksilver']
e = enumerate(avengers)
print(type(e))
<class 'enumerate'>
e_list = list(e)
print(e_list)
0 hawkeye
1 iron man
2 thor
3 quicksilver
10 hawkeye
11 iron man
12 thor
13 quicksilver
z = zip(avengers, names)
print(type(z))
<class 'zip'>
z_list = list(z)
print(z_list)
hawkeye barton
iron man stark
thor odinson
quicksilver maximoff
Hugo Bowne-Anderson
Data Scientist at DataCamp
Loading data in chunks
There can be too much data to hold in memory
result.append(sum(chunk['x']))
total = sum(result)
print(total)
4252532
print(total)
4252532
Hugo Bowne-Anderson
Data Scientist at DataCamp
What’s next?
List comprehensions and generators
List comprehensions:
Create lists from other lists, DataFrame columns, etc.