Introducción a los iteradores

Caja de herramientas Python

Hugo Bowne-Anderson

Data Scientist at DataCamp

Iterar con un bucle for

  • Podemos iterar sobre una lista con un bucle for
employees = ['Nick', 'Lore', 'Hugo']

for employee in employees: print(employee)
Nick
Lore
Hugo
Caja de herramientas Python

Iterar con un bucle for

  • Podemos iterar sobre una cadena con un bucle for
for letter in 'DataCamp':
    print(letter)
D
a
t
a
C
a
m
p
Caja de herramientas Python

Iterar con un bucle for

  • Podemos iterar sobre un objeto range con un bucle for
for i in range(4):
    print(i)
0
1
2
3
Caja de herramientas Python

Iteradores vs. iterables

  • Iterable
    • Ejemplos: listas, cadenas, diccionarios, archivos
    • Objeto con un método iter() asociado
    • Aplicar iter() a un iterable crea un iterador
  • Iterador
    • Produce el siguiente valor con next()
Caja de herramientas Python

Iterar sobre 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:
Caja de herramientas Python

Iterar de una vez con *

word = 'Data'
it = iter(word)

print(*it)
D a t a
print(*it)
  • ¡No quedan más valores!
Caja de herramientas Python

Iterar sobre diccionarios

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

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

Iterar sobre archivos

file = open('file.txt')
it = iter(file)

print(next(it))
This is the first line.
print(next(it))
This is the second line.
Caja de herramientas Python

¡Vamos a practicar!

Caja de herramientas Python

Preparing Video For Download...