Enumerate Intermediate Python Tutorial part 7
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.
-
Intermediate Python Programming introduction
-
String Concatenation and Formatting Intermediate Python Tutorial part 2
-
Argparse for CLI Intermediate Python Tutorial part 3
-
List comprehension and generator expressions Intermediate Python Tutorial part 4
-
More on list comprehension and generators Intermediate Python Tutorial part 5
-
Timeit Module Intermediate Python Tutorial part 6
-
Enumerate Intermediate Python Tutorial part 7
-
Python's Zip function
-
More on Generators with Python
-
Multiprocessing with Python intro
-
Getting Values from Multiprocessing Processes
-
Multiprocessing Spider Example
-
Introduction to Object Oriented Programming
-
Creating Environment for our Object with PyGame
-
Many Blobs - Object Oriented Programming
-
Blob Class and Modularity - Object Oriented Programming
-
Inheritance - Object Oriented Programming
-
Decorators in Python Tutorial
-
Operator Overloading Python Tutorial
-
Detecting Collisions in our Game Python Tutorial
-
Special Methods, OOP, and Iteration Python Tutorial
-
Logging Python Tutorial
-
Headless Error Handling Python Tutorial
-
__str__ and __repr_ in Python 3
-
Args and Kwargs
-
Asyncio Basics - Asynchronous programming with coroutines
