How to Use enumerate() in Python

Publicado el: 28 abril 2021
en el canal de: DataDaft
44,656
1.5k

Code available in comment below! This video shows the basics of how to use enumerate() in Python. enumerate() is useful for looping through data structures like lists while having access to each index and the corresponding value for each iteration of the loop.


characters = ["Krillin","Goku", "Vegeta", "Gohan", "Piccolo"]

enumerate() returns a sequence of (index, item) tuples

list(enumerate(characters))

Use enumerate() in a for loop to get an item and its index

for index, character in enumerate(characters):
print(index, character)

Why might you want to use enumerate?
Example: store index positions of duplicate items

characters = ["Krillin","Goku", "Goku", "Gohan", "Piccolo",
"Krillin","Goku", "Vegeta", "Gohan", "Piccolo",
"Piccolo","Goku", "Vegeta", "Goku", "Piccolo"]

character_map = {character:[] for character in set(characters)}

print(character_map)

Use enumerate to store the index for each occurence
for index, character in enumerate(characters):
character_map[character].append(index)

character_map


En esta página del sitio puede ver el video en línea How to Use enumerate() in Python de Duración hora minuto segunda en buena calidad , que subió el usuario DataDaft 28 abril 2021, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 44,656 veces y le gustó 1.5 mil a los espectadores. Disfruta viendo!