Python Zip Details
Python Zip Details
wise into tuples. It returns an iterator of tuples, where each tuple contains one element from each of
the iterables.
Syntax:
python
Copy code
zip(*iterables)
Example:
python
Copy code
list1 = [1, 2, 3]
print(list(zipped))
Output:
css
Copy code
The zip() func on stops when the shortest input iterable is exhausted.
Unzipping:
python
Copy code
unzipped = zip(*zipped)
print(list1) # (1, 2, 3)
4o
You said:
What about the one list is having higher length then the another one
ChatGPT said:
ChatGPT
When the lists have different lengths, the zip() func on stops when the shortest iterable is
exhausted. It doesn't fill in or extend the shorter list; it just pairs up elements up to the length of the
shortest iterable and ignores the remaining elements in the longer ones.
Example:
python
Copy code
list1 = [1, 2, 3, 4]
print(list(zipped))
Output:
css
Copy code
In this case, since list2 has only 2 elements, zip() stops a er pairing the first 2 elements, ignoring the
remaining elements in list1.
If you want to handle the situa on where lists have different lengths (for example, filling missing
values), you can use itertools.zip_longest() from the itertools module, which allows specifying a fill
value for shorter lists.
python
Copy code
list1 = [1, 2, 3, 4]
print(list(zipped))
Output: