Welcome back to Day 31 of the 100 Days of Python journey!
Today, we dive into three powerful and often underused Python features that can make your code cleaner, shorter, and more expressive:
enumerate()
zip()
- Tuple unpacking
Letโs break each of these down with simple examples. ๐ง
๐ข 1. enumerate()
โ Get Index and Value in Loops
When looping through a list, you sometimes need both the index and the value.
Instead of using a range(len())
combo, use enumerate()
:
โ
Without enumerate()
:
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(i, fruits[i])
โ
With enumerate()
:
for index, fruit in enumerate(fruits):
print(index, fruit)
๐งช Output:
0 apple
1 banana
2 cherry
You can even specify a custom starting index:
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)
๐ 2. zip()
โ Pairing Elements from Multiple Lists
The zip()
function allows you to combine multiple iterables (like lists or tuples) element-wise.
โ Example:
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
๐งช Output:
Alice scored 85
Bob scored 92
Charlie scored 78
โ ๏ธ What if the lists have different lengths?
zip()
stops at the shortest iterable.
a = [1, 2, 3]
b = ['x', 'y']
print(list(zip(a, b))) # Output: [(1, 'x'), (2, 'y')]
To fill missing values, use itertools.zip_longest()
.
๐ 3. Unpacking โ Split Values into Variables
Python lets you unpack values from lists, tuples, or zip results directly into variables.
โ Example:
person = ("John", 25, "Engineer")
name, age, job = person
print(name) # John
print(age) # 25
print(job) # Engineer
You can even unpack inside loops:
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
for number, word in pairs:
print(f"{number} = {word}")
๐ฏ Bonus: Using _
to Ignore Values
If you want to ignore a value during unpacking:
data = ("Tom", 30, "Doctor")
name, _, profession = data
The underscore (_
) is commonly used as a throwaway variable.
๐ Why These Tools Matter
Tool | Use Case |
---|---|
enumerate() |
Get index + value while looping |
zip() |
Combine iterables element-wise |
Unpacking | Clean extraction of values |
Using these tools makes your code more readable, less error-prone, and more Pythonic.
๐ง Practice Challenge
students = ['Emma', 'Liam', 'Olivia']
grades = [91, 88, 95]
# Task: Print "1. Emma scored 91" and so on...
Try solving this using enumerate()
and zip()
together!
Top comments (0)