Home > Backend Development > Python Tutorial > Why Does Zipping Three 20-Element Lists in Python Result in a 20-Element List?

Why Does Zipping Three 20-Element Lists in Python Result in a 20-Element List?

Susan Sarandon
Release: 2024-12-09 20:05:10
Original
886 people have browsed it

Why Does Zipping Three 20-Element Lists in Python Result in a 20-Element List?

Zipping Lists in Python

In Python, the 'zip()' function combines multiple lists into a single list of tuples. Each tuple contains elements from corresponding positions in the input lists.

Question:

A user encountered an unexpected result while zipping three lists of size 20 each. Contrary to their expectation of three elements, the zipped list had 20 elements.

Answer:

When zipping multiple lists, the resulting list contains as many elements as the shortest input list. In this case, all three input lists have 20 elements, so the zipped list also has 20 elements. However, each element is a three-tuple, containing elements from corresponding positions in the three input lists.

Example:

a = b = c = range(20)
result = zip(a, b, c)

print(len(result))  # 20
print(len(result[0]))  # 3
Copy after login

Conclusion:

Zipping lists creates a new list where each element is a tuple of elements from the corresponding positions in the input lists. The length of the zipped list matches the shortest input list, while the length of each tuple matches the number of input lists.

The above is the detailed content of Why Does Zipping Three 20-Element Lists in Python Result in a 20-Element List?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template