10 Essential Use Cases of Python's zip() Function with Examples

10 Essential Use Cases of Python's zip() Function with Examples

1. Combining Two Lists

Use case: Merging two lists element-wise.

In?[3]:

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

combined = list(zip(names, ages))
print(combined)  
        
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]
        

2. Unzipping Lists

Use case: Splitting paired data into separate lists.

In?[6]:

combined = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

names, ages = zip(*combined)
print(names)  
print(ages)   
        
('Alice', 'Bob', 'Charlie')
(25, 30, 35)
        

3. Iterating Over Multiple Lists Simultaneously

Use case: Useful when you need to iterate through multiple lists at the same time.

In?[9]:

subjects = ['Math', 'Science', 'English']
scores = [88, 92, 85]

for subject, score in zip(subjects, scores):
    print(f"{subject}: {score}")
        
Math: 88
Science: 92
English: 85
        

4. Creating Dictionaries

Use case: Creating dictionaries from two lists: one for keys, one for values.

In?[12]:

keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']

dictionary = dict(zip(keys, values))
print(dictionary)  
        
{'name': 'Alice', 'age': 25, 'city': 'New York'}
        

5. Combining Multiple Lists

Use case: Zipping more than two lists together.

In?[15]:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False, True]

combined = list(zip(list1, list2, list3))
print(combined)  
        
[(1, 'a', True), (2, 'b', False), (3, 'c', True)]
        

6. Handling Different Length Iterables

Use case: When lists have different lengths, zip() stops at the shortest one.

In?[18]:

list1 = [1, 2, 3]
list2 = ['a', 'b']

combined = list(zip(list1, list2))
print(combined)  
        
[(1, 'a'), (2, 'b')]
        

7. Working with Ranges

Use case: Zipping together ranges or sequences.

In?[21]:

numbers = range(1, 4)
letters = ['a', 'b', 'c']

result = list(zip(numbers, letters))
print(result)  
        
[(1, 'a'), (2, 'b'), (3, 'c')]
        

8. Comparing Elements of Two Lists

Use case: Zipping two lists to compare elements.

In?[24]:

list1 = [1, 2, 3]
list2 = [1, 4, 3]

comparison = [a == b for a, b in zip(list1, list2)]
print(comparison)
        
[True, False, True]
        

9. Transpose a Matrix

Use case: Use zip() to transpose rows and columns of a 2D matrix.

In?[27]:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

transposed = list(zip(*matrix))
print(transposed) 
        
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        

10. Zipping with Enumerate

Use case: Zipping with an enumerated list for indexed pairings.

In?[30]:

data = ['apple', 'banana', 'cherry']
indexed_data = list(zip(range(1, len(data) + 1), data))
print(indexed_data)  
        
[(1, 'apple'), (2, 'banana'), (3, 'cherry')]        
Austin Makachola

Founder Goldmann Global, Betwise, Greenware| Software Engineer| World history and diplomacy expert.

3 周

Thank you

回复
Krzysztof Ma?ek

Software developer // Python, Web apps, APIs // ???? Hledám práci v Praze ????

1 个月

9. What a neat trick! Love it

要查看或添加评论,请登录

社区洞察

其他会员也浏览了