📦

How to use the 'zip()' in python

2024/06/30に公開

1. zip()

zip() get the array like input as augments, and return the tuple that packed both of input.

・Example

# Example lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]

# Use zip to combine the lists
zipped = zip(keys, values)

# Convert the zipped object to a list of tuples and print it
zipped_list = list(zipped)
print(zipped_list)
[('a', 1), ('b', 2), ('c', 3)]

2. When it helps?

It is helpful when you wanna make a dictionary from array:

# Example lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]

# Use zip to combine the lists and create a dictionary
dictionary = dict(zip(keys, values))

# Print the dictionary
print(dictionary)
[('a', 1), ('b', 2), ('c', 3)]

If the inputs length are different, large one truncated to fit the smaller one.

Also, we can fit to large one and fill the missing value.
・Example

from itertools import zip_longest

# Example lists with different lengths
keys = ['a', 'b', 'c']
values = [1, 2]

# Use zip_longest to combine the lists with a fill value of None
zipped_longest = zip_longest(keys, values, fillvalue=None)

# Convert the zipped_longest object to a list of tuples and print it
zipped_list_longest = list(zipped_longest)
print(zipped_list_longest)
[('a', 1), ('b', 2), ('c', None)]

In some cases this can be very useful.

Discussion