enumerate() function in python

There are many situations where we’ll need to iterate over multiple lists in tandem, such as this one:enumurate fn

In the example above, we have two lists. The second list describes the viciousness of the animals in the first list. A Dog has a viciousness level of 1, and a SuperLion has a viciousness level of 10. We want to retrieve the position of the item in animals the loop is currently on, so we can use it to look up the corresponding value in the viciousness list.

Unfortunately, we can’t just loop through animals, and then tap into the second list. Python has an enumerate() function that can help us with this, though. The enumerate() function allows us to have two variables in the body of a for loop — an index, and the value.

On every iteration of the loop, the value for i will become the value of the index in animals that corresponds to that iteration. animal will take on the value in animals that corresponds to the index i.

Here’s another example of how we can use the enumerate() function to iterate over multiple lists in tandem:

enumurate fn2

In this example, we use the index variable i to index the cars list, and print the cars value that corresponds to the same index in ship list. look at the comments for details.

Leave a comment