Enumerate and Zip Functions in Python (31/100 Days of Python)
Python has two built-in functions that can be extremely useful when working with sequences such as lists, tuples, and strings. These functions are called enumerate and zip. In this tutorial, we’ll be discussing what these functions do and how you can use them in your code.
Enumerate
The enumerate
function adds a counter to an iterable and returns it in a form of an enumerate object. This object can be converted into a list of tuples containing the index and the corresponding item in the iterable:
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit)
# Will print:
# 0 apple
# 1 banana
# 2 cherry
As you can see, enumerate
starts the counter from 0 by default, but you can specify a starting value by passing a second argument to the function.
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits, 1):
print(i, fruit)
# Will print:
# 1 apple
# 2 banana
# 3 cherry
Zip
The zip
function is used to combine two or more iterables into a single iterable. The items in the resulting iterable are formed by taking corresponding items from each iterable:
fruits = ['apple', 'banana', 'cherry']
colors = ['red', 'yellow', 'red']
for fruit, color in zip(fruits, colors):
print(fruit, color)
# Will print:
# apple red
# banana yellow
# cherry red
Note that the length of the resulting iterable is equal to the length of the shortest input iterable.
fruits = ['apple', 'banana', 'cherry']
colors = ['red', 'yellow']
for fruit, color in zip(fruits, colors):
print(fruit, color)
# Output:
# apple red
# banana yellow
So, enumerate
and zip
are two useful utility functions in Python that can help you simplify your code and make it more “Pythonic”. Try using them in your next project and see the difference it makes!
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — zip and enumerate
- Full series: 100 Days of Python
- Previous topic: Python Variable Scope
- Next topic: Lambda Functions in Python: A Comprehensive Guide to Understanding and Using Anonymous Functions