0% found this document useful (0 votes)
8 views

Python Zip Details

how to get read the python zip

Uploaded by

chetanrodrigues
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Zip Details

how to get read the python zip

Uploaded by

chetanrodrigues
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

In Python, the zip() func on is used to combine two or more iterables (like lists or tuples) element-

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]

list2 = ['a', 'b', 'c']

zipped = zip(list1, list2)

print(list(zipped))

Output:

css

Copy code

[(1, 'a'), (2, 'b'), (3, 'c')]

The zip() func on stops when the shortest input iterable is exhausted.

Unzipping:

You can also "unzip" a zipped list of tuples using * operator:

python

Copy code

zipped = [(1, 'a'), (2, 'b'), (3, 'c')]

unzipped = zip(*zipped)

list1, list2 = list(unzipped)

print(list1) # (1, 2, 3)

print(list2) # ('a', 'b', 'c')

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]

list2 = ['a', 'b']

zipped = zip(list1, list2)

print(list(zipped))

Output:

css

Copy code

[(1, 'a'), (2, 'b')]

In this case, since list2 has only 2 elements, zip() stops a er pairing the first 2 elements, ignoring the
remaining elements in list1.

Handling Different Lengths:

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.

Example with zip_longest:

python

Copy code

from itertools import zip_longest

list1 = [1, 2, 3, 4]

list2 = ['a', 'b']

zipped = zip_longest(list1, list2, fillvalue='NA')

print(list(zipped))
Output:

You might also like