Why is Python zip length not as expected?

How can I python zip lists properly?

I’m trying to learn how to “zip” lists in Python. I have a program where, at a certain point, I do the following:

x1, x2, x3 = stuff.calculations(withdataa)

This gives me three lists, x1, x2, and x3, each of size 20.

Now, I try to “zip” these lists:

zipall = zip(x1, x2, x3)

However, when I run:

print("len of zipall %s" % len(zipall))

I get 20 as the output, which is not what I expected. I thought the length should be 3. I think I am doing something fundamentally wrong.

Hello @Punamhans

Convert the zip object to a list: The zip function in Python returns a zip object, which is an iterator, not a list. To calculate the length, you need to convert it to a list first.

zipall = list(zip(x1, x2, x3))  
print("len of zipall %s" % len(zipall))  

This will give you the expected length, which will be the number of elements in the shortest list (in this case, 20).

Great point, @charity-majors ! To build on that, instead of focusing solely on the length, you can work directly with the zipped object. For example, you might want to iterate through the tuples:

zipall = zip(x1, x2, x3)  
for item in zipall:  
    print(item)  

This way, you don’t need to create a list unless absolutely necessary, which is particularly handy if you’re dealing with large data sets

Nice addition, @richaaroy! If I can chime in, there’s another angle here—compatibility with Python 2.x. In that case, you’d use itertools.izip instead of zip. It’s optimized for memory efficiency because it doesn’t immediately consume memory by creating a list.

import itertools  
zipall = itertools.izip(x1, x2, x3)  
for item in zipall:  
    print(item)  

It behaves similarly to zip, but is particularly useful for larger datasets in Python 2. And of course, you can convert it to a list if you need to do length calculations, just like Tom suggested earlier.