Enumerate

A for loop in Python is used to iterate over iterables (lists, tuples and even strings). In the previous tutorial you learned all you need to know about for loops.

What About keeping track?

It is a very common need when iterating over a list or a tuple to keep count of the iteration.
That is why python has the enumerate() built-in function. enumerate() returns the next item in the iterable along with its index!

Here is an example:

#enumerate my_list = ["Apollo", "Elvis", "Oliver", "Zeus"] for item in enumerate(my_list): print(item) #Here we print the names with an odd index: for counter, name in enumerate(my_list): if counter % 2: print(name)

Using the enumerate() function we can easily proccess items and their indexes. For example we can choose to print out only the items with odd indexes:

#enumerate my_list = ["Apollo", "Elvis", "Oliver", "Zeus"] #Here we print the names with an odd index: for counter, name in enumerate(my_list): if counter % 2: print(name)

Exercise

  1. Create a list.
  2. Print out the items in an index that can be divided by 3.

#Write your code here