loading...

Python's enumerate function

micahsgilbert profile image Micah Gilbert Updated on ・2 min read

This is just a quick post because I've seen some python beginners make some functions that are really in need of enumerate, but they don't know it and turn to odd solutions.

What does it do?

Put simply, enumerate is a function that takes in an iterable (typically an array) and, for each item, gives both its index in the array and the item itself.

When should I use it?

I've seen this:

array = ["a","b","c","b"]
for index in range(len(array)):
    item = array[i]
    # code continues using both `index` and `item`

This really doesn't hurt too much but enumerate can make this a bit cleaner.

In my early days of Python I created a monstrosity like this:

array = ["a","b","c","b"]
for item in array:
    index = array.index(item)
    # code continues using both `index` and `item`

This is actively bad code, and my thinking "There must be a better way to do this" finally led me to enumerate.
The main issue with this, other than possible performance issues if the array is quite long, is that array.index only returns the first index of the item. That means that the second "b" in the array will never get its index (3) run in the rest of the for loop. Instead, array.index will return 1 for both "b"s.

How should I use it?

enumerate is incredible easy. All that is needed is:

array = ["a","b","c","b"]
for index, item in enumerate(array)
    # code continues using both `index` and `item`

Look at how clean that is. That uses fewer lines than both code blocks above, and is arguably the most explicit and easiest to understand.

List comprehensions can also be used for filtering lists.

Let's say that we want all odd-indexed items that are vowels.

test_letters = ["a", "e", "i", "q", "c"]
vowels = ('a','e','i','o','u')

# Not using `enumerate`, just plain old logic
# This ca be confusing, especially if it wasn't documented.

new_arr = []
for i in range(len(test_letters)):
    if i % 2 == 0 and test_letters[i] in vowels:
        new_arr.append(test_letters[i])


# With enumerate
# It's only one line and still makes a ton of sense.

new_arr = [letter for index,letter in test_letters if index % 2 == 0 and letter in enumerate(vowels)]

enumerate is an incredibly useful function, and anyone learning Python should be using it.

Posted on by:

Discussion

markdown guide
 

Last line of your code:

new_arr = [letter for index,letter in test_letters if index % 2 == 0 and letter in vowels]

you forgot to actually use the enumerate function 😂😂

 

Wow! I can't believe I missed that. Fixed.