Home >Backend Development >Python Tutorial >Why Does `zip()` in Python Return a List of 20 Tuples When Combining Three Lists?
In Python programming, the zip() function plays a crucial role in combining multiple lists into a single list of tuples. Each tuple represents a row, pairing corresponding elements from the input lists.
Consider the following code snippet:
x1, x2, x3 = stuff.calculations(withdataa) zipall = zip(x1, x2, x3) print("len of zipall %s" % len(zipall))
Unlike the expected result of three, the output is 20, indicating a fundamental misunderstanding.
When you zip together three lists with 20 elements each, the resulting list contains 20 tuples. Each tuple contains three elements, one from each of the input lists.
For instance:
In [1]: a = b = c = range(20) In [2]: zip(a, b, c) Out[2]: [(0, 0, 0), (1, 1, 1), ... (17, 17, 17), (18, 18, 18), (19, 19, 19)]
To determine the length of each tuple, you can inspect the first element:
In [3]: result = zip(a, b, c) In [4]: len(result[0]) Out[4]: 3
However, this approach may fail if the input lists are empty. Therefore, it's best to use a more robust method to determine the number of elements in each tuple.
The above is the detailed content of Why Does `zip()` in Python Return a List of 20 Tuples When Combining Three Lists?. For more information, please follow other related articles on the PHP Chinese website!