items1 = ["blue", "red", "green", "white"]
items2 = ["sky", "sunset", "lawn", "pillow"]
# Zip the two lists and access pairs together.
for item1, item2 in zip(items1, items2):
print(item1, "...", item2)blue ... sky
red ... sunset
green ... lawn
white ... pillow
Unequal length. When we call zip, the function must find the largest common element count. So if one list has 4 elements and the other 3, the zip object will have just 3 tuples in it.
list1 = [10, 20, 30, 40]
list2 = [11, 21, 31]
# Zip the two lists.
result = zip(list1, list2)
# The zipped result is only 3 elements long.# ... The fourth element of list1 was discarded.
for element1, element2 in result:
print(element1, element2)10 11
20 21
30 31
Zip object. Zip does not return a list. Instead it returns a special, optimized collection called a "zip object." We can loop over the zip object, but cannot access by indexes.
list1 = [0]
list2 = [1]
# The result is a zip object.
result = zip(list1, list2)
print(result)<zip object at 0x02884120>
Not subscriptable. A zip object is not a list. We cannot access each element directly with an index. Instead we must loop over the result of zip or convert it.
Detail We cause TypeErrors when we try to use unavailable functions on zip objects. Please see the "convert to list" example.
list1 = [0, 1, 2]
list2 = [3, 4, 5]
# Zip together the two lists.
zipped = zip(list1, list2)
# This causes an error.
print(zipped[0])Traceback (most recent call last):
File "C:\programs\file.py", line 12, in <module>
print(zipped[0])
TypeError: 'zip' object is not subscriptable
Len error. We cannot take the len of a zip object. This will result in a TypeError and a message stating "zip has no length." Please first convert to a list.
zipped = zip([1, 2], [3, 4])
# This causes an error.
print(len(zipped))Traceback (most recent call last):
File "C:\programs\file.py", line 7, in <module>
print(len(zipped))
TypeError: 'zip' has no length
Convert to list. Zip objects are not the most useful things. For many operations, a list is more effective. We can convert a zip object into a list with the list built-in function.
# Zip up these two lists.
zipped = zip([1, 2], [3, 4])
# Convert the zip object into a list.
result_list = list(zipped)
print(result_list)[(1, 3), (2, 4)]
In a sense, zip() lets us treat 2 single-dimension lists as one list of pairs—a two-dimensional list. More than two lists can be zipped—try passing 3 or more lists to zip.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.