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.
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.
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
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
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.