How to Use the zip() Function with Tuples in Python

How to Use the zip() Function with Tuples in Python

The zip() function in Python is used to combine multiple iterables into a single iterable of tuples. Each tuple contains elements from the corresponding positions of the input iterables. Here are five examples demonstrating the use of the zip() function with tuples:

  1. Combining Two Lists into Tuples:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Using zip() to combine lists into tuples
result = list(zip(list1, list2))
print(result)  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
  1. Combining Lists of Different Lengths into Tuples:
list1 = [1, 2, 3]
list2 = ['a', 'b']

# Using zip() to combine lists into tuples
result = list(zip(list1, list2))
print(result)  # Output: [(1, 'a'), (2, 'b')]
# Note: The zip() function truncates the result to the shortest input iterable.
  1. Combining Tuple Elements with a List:
tuple1 = (1, 2, 3)
list1 = ['a', 'b', 'c']

# Using zip() to combine tuple elements with a list
result = list(zip(tuple1, list1))
print(result)  # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
  1. Combining Multiple Iterables into Tuples:
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
booleans = [True, False, True]

# Using zip() to combine multiple iterables into tuples
result = list(zip(numbers, letters, booleans))
print(result)  # Output: [(1, 'a', True), (2, 'b', False), (3, 'c', True)]
  1. Unzipping Tuples into Separate Lists:
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]

# Using zip() with the * operator to unzip tuples into separate lists
numbers, letters = zip(*pairs)
print(numbers)  # Output: (1, 2, 3)
print(letters)  # Output: ('a', 'b', 'c')

In each example, the zip() function is used to combine iterables into tuples. It can handle multiple input iterables of different types, and the resulting tuples contain elements from the same index position across all input iterables.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!