Wednesday, 21 August 2024

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

 

1. Combining Two Lists

Use case: Merging two lists element-wise.

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.


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.


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.


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.


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.


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.


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.


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.


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.


data = ['apple', 'banana', 'cherry']

indexed_data = list(zip(range(1, len(data) + 1), data))

print(indexed_data)  

[(1, 'apple'), (2, 'banana'), (3, 'cherry')]

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (351) Python Quiz (21) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses