In Python, the built-in function zip() aggregates multiple iterable objects (lists, tuples, etc.). You can iterate multiple lists in the for loop with zip() . - Built-in Functions - zip() — Python 3.8.5 documentation
This article describes the following contents. - Iterate two, three, or more lists with
zip() - In the case that number of
elements is different
zip() ignores the extra elements- The
strict parameter of zip() (Python3.10 or later) itertools.zip_longest() fills in the missing elements
- Get a list of multiple iterable elements
Iterate two, three, or more lists with zip()By passing two lists to zip() , you can iterate them in the for loop. names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for name, age in zip(names, ages):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18
The same applies not only to two lists but also
to three or more lists. points = [100, 85, 90]
for name, age, point in zip(names, ages, points):
print(name, age, point)
# Alice 24 100
# Bob 50 85
# Charlie 18 90
You can specify other iterable objects as well as lists. In the case that number of elements is differentIf the number of elements of each iterable object is different, zip() ignores the extra elements. names = ['Alice', 'Bob', 'Charlie', 'Dave']
ages = [24, 50, 18]
for name, age in zip(names, ages):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18
The strict parameter of zip() (Python3.10 or later)The strict parameter was added to
zip() in Python 3.10. Note that it is not available in 3.9 or earlier. If strict=True , an error is raised if the number of elements is different. # for name, age in zip(names, ages, strict=True):
# print(name, age)
# ValueError: zip() argument 2 is shorter than argument 1
The default is strict=False , which is the same behavior as up to 3.9, i.e., extra elements are ignored. With itertools.zip_longest() , you can fill the missing elements with any values. - itertools.zip_longest() — Functions creating iterators for efficient looping — Python 3.8.5 documentation
By default, it is filled with None . from itertools import zip_longest
names = ['Alice', 'Bob', 'Charlie', 'Dave']
ages = [24, 50, 18]
for name, age in zip_longest(names, ages):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18
# Dave None
You can specify the value to fill in the fillvalue parameter. for name, age in zip_longest(names, ages, fillvalue=20):
print(name, age)
# Alice 24
# Bob 50
# Charlie 18
# Dave 20
The value to be filled is uniform even if there are multiple lists with insufficient elements. You cannot specify different values.
points = [100, 85]
for name, age, point in zip_longest(names, ages, points, fillvalue=20):
print(name, age, point)
# Alice 24 100
# Bob 50 85
# Charlie 18 20
# Dave 20 20
If you want to fill multiple lists with unknown numbers of elements with different values, follow the procedure below. - Define the value to fill for all lists
- Get the maximum number of elements
- Fill all lists up to the maximum number of elements
- Aggregate with
zip()
fill_name = 'XXX'
fill_age = 20
fill_point = 50
len_names = len(names)
len_ages = len(ages)
len_points = len(points)
max_len = max(len_names, len_ages, len_points)
names = names + [fill_name] * (max_len - len_names)
ages = ages + [fill_age] * (max_len - len_ages)
points = points + [fill_point] * (max_len - len_points)
print(names)
print(ages)
print(points)
# ['Alice', 'Bob', 'Charlie', 'Dave']
# [24, 50, 18, 20]
# [100, 85, 50, 50]
for name, age, point in zip(names, ages, points):
print(name, age, point)
# Alice 24 100
# Bob 50 85
# Charlie 18 50
# Dave 20 50
The process of filling the list to the maximum number of elements uses initialization and concatenation of lists. - Initialize a list with given size and values in Python
- Add an item to a list in Python (append, extend, insert)
It can be a function like this: def my_zip_longest(iterables, fillvalues):
max_len = max(len(i) for i in iterables)
return zip(*[list(i) + [v] * (max_len - len(i)) for i, v in zip(iterables, fillvalues)])
for name, age, point in my_zip_longest((names, ages, points), ('XXX', 20, 50)):
print(name, age, point)
# Alice 24 100
# Bob 50 85
# Charlie 18 50
# Dave 20 50
It uses list comprehensions and list unpacking by * . - List
comprehensions in Python
- Unpack and pass list, tuple, dict to function arguments in Python
Get a list of multiple iterable elementszip returns an iterator (zip object) that contains tuple with the elements of multiple iterable objects.
names = ['Alice', 'Bob', 'Charlie']
ages = (24, 50, 18)
z = zip(names, ages)
print(z)
print(type(z))
# <zip object at 0x1038b0980>
# <class 'zip'>
It can be converted to a list with list() . l = list(zip(names, ages))
print(l)
print(type(l))
print(type(l[0]))
# [('Alice', 24), ('Bob', 50), ('Charlie', 18)]
# <class 'list'>
# <class 'tuple'>
Can we zip multiple lists in Python?
zip() in Python: Get elements from multiple lists. In Python, the built-in function zip() aggregates multiple iterable objects (lists, tuples, etc.). You can iterate multiple lists in the for loop with zip() .
How do I zip 3 lists in Python?
Python zip three lists
Python zipping of three lists by using the zip() function with as many inputs iterables required. The length of the resulting tuples will always equal the number of iterables you pass as arguments.
What happens when you zip two lists in Python?
Zipping two lists pairs elements from the first list with elements from the second list. For example, zipping [1, 2, 3] and [4, 5, 6] results in [(1, 4), (2, 5), (3, 6)] .
How do I zip multiple files in Python?
Create a zip archive from multiple files in Python
Create a ZipFile object by passing the new file name and mode as 'w' (write mode). It will create a new zip file and open it within ZipFile object. Call write() function on ZipFile object to add the files in it. call close() on ZipFile object to Close the zip file.
|