Python for Programmers: Enumerate Function
Welcome to the Enumerate Function lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Python doesn't have the common C-style
forloop:for (i = 0; i < max; i++). Instead, it only has a "for-each" loop:for value in values. That's great, except when we need to know both the value and its index in the list.The
enumeratebuilt-in solves that problem. It takes an iterable like["a", "b"]and returns a list of tuples with the indexes and values, like[(0, 'a'), (1, 'b')].>
my_list = ["a", "b"]list(enumerate(my_list))Result:
In the next example, we use
enumerateto find the index of'a'in our list.>
data = ["c", "b", "a"]found_index = Nonefor index, value in enumerate(data):if value == "a":found_index = indexfound_indexResult:
2
enumerateworks on any iterable, not just lists. For example, we can use it with strings. Normally, indexing into a string gives us a one-character string containing the character at that index.>
"cat"[1]Result:
'a'
Using
enumerateon a string gives us a list of tuples holding the index and the character, similar to what we saw above for lists.>
list(enumerate("cat"))Result:
>
list(enumerate("do"))Result:
[(0, 'd'), (1, 'o')]
The next example defines a treasure map. It's a list of strings, with each string representing one row in the map. We can
enumeratethe rows (strings in the list) and columns (characters in each string) to find the treasure, marked by X.>
treasure_map = ["........","....#..#","#....#..","....X.#.",".#......","......#.","#.......","........",]for (row_coordinate, row) in enumerate(treasure_map):for (col_coordinate, c) in enumerate(row):# X marks the spot!if c == "X":location = (row_coordinate, col_coordinate)locationResult:
(3, 4)
We can also
enumeratea dictionary's keys. That gives us the keys in their original insertion order. As usual, each one is packed into a tuple along with its index.>
cat_ages = {"Ms. Fluff": 4,"Keanu": 2,}list(enumerate(cat_ages))Result:
[(0, 'Ms. Fluff'), (1, 'Keanu')]
Here's a code problem:
The code below defines a list of users. Each user is a dictionary with a
"name"key. Write auser_indexfunction that takes a user's name, finds that user in the list, and returns their list index. If no user has that name, it should returnNone.def user_index(users, name):for (idx, user) in enumerate(users):if user["name"] == name:return idxreturn Noneusers = [{"name": "Betty"},{"name": "Cindy"},{"name": "Amir"},{"name": "Gabriel"},{"name": "Hana"},]assert user_index(users, "Amir") == 2assert user_index(users, "Betty") == 0assert user_index(users, "Cindy") == 1assert user_index(users, "Dalili") is None- Goal:
No errors.
- Yours:
No errors.