Friday, January 3, 2025

Using zip() to Combine Lists in Python


In Python, the zip() function is a powerful and efficient way to combine multiple lists into a single iterable. It pairs elements from each list into tuples, making it easy to handle parallel data.
names = ['John', 'Alice', 'Bob']
ages = [25, 30, 35]
combined = zip(names, ages)
for name, age in combined:
    print(f"{name} is {age} years old.")
Syntax: zip(iterable1, iterable2, ...)

zip() stops when the shortest list is exhausted.
Convert the result to a list or any other collection type for further use. 

zip() is great for combining data, especially in scenarios like parallel iteration and data manipulation.

No comments:

Search This Blog