Member-only story
Zip Functions in Python
The zip() function in Python is a built-in function that allows you to combine multiple iterables (such as lists, tuples, or strings) element-wise into a single iterable. It pairs up elements from each iterable, creating tuples of corresponding elements.
Here’s how the zip() function works:
# Syntax
zip(iterable1, iterable2, …)- Zip function on List data type:
# Example
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2) #The result is a zip object, which is an iterator of tuples
print(list(zipped)) #You can convert this zip object into a list of tuples using list(),
# Output: [(1, 'a'), (2, 'b'), (3, 'c')]It’s important to note that if the input iterables passed to zip() are of different lengths, the resulting zip object will have a length equal to the shortest input iterable. Any excess elements from longer iterables will be ignored.
2. Zip function on Tuples Data Type:
# Tuples
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
# Using zip with tuples
zipped = zip(tuple1, tuple2)
print(list(zipped))
# Output: [(1, 'a'), (2, 'b'), (3, 'c')]3. Zip function on String Data Type:
# Strings
string1 = "hello"
string2 = "world"
# Using zip with strings
zipped = zip(string1, string2)
print(list(zipped))
# Output: [('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd')]






