Welcome to part 7 of the intermediate Python programming tutorial series. In this part, we're going to talk about the built-in function: enumerate.
A somewhat common task might be to attempt to attach an index value, or some other unique value to list items. Maybe something like this looks vaguely familiar:
example = ['left','right','up','down'] for i in range(len(example)): print(i, example[i])
0 left 1 right 2 up 3 down
Instead, you can do:
for i,j in enumerate(example): print(i,j)
The enumerate function returns a tuple containing the count, and then the actual value from the iterable.
That iterable can be a dict:
example_dict = {'left':'<','right':'>','up':'^','down':'v',} [print(i,j) for i,j in enumerate(example_dict)]
You can even create new dicts with a list and enumerate:
new_dict = dict(enumerate(example)) print(new_dict)
The last example is one I have used to store objects, using enumerate to make a sort of unique id for them.
That's all for enumerate! In the next tutorial, we're going to cover the zip
function.