Python

How to Use Zip Function in Python

This article will cover a guide on “zip” function available in Python’s standard module library. This method allows you to combine and pair elements of multiple iterable objects. You can then run further logic on these pairs. In many cases, using a “zip” function is much more efficient and cleaner than using multiple, nested “for” loops.

About Zip Function

As stated earlier, “zip” function is used to create pairs from elements of multiple iterable objects. Consider the example below to understand the basic syntax and usage of zip function:

list1 = ["a", "b", "c"]
list2 = ["apple", "ball", "cat"]
zipped = zip(list1, list2)
print (list(zipped))

The first two statements in the above code sample define two lists containing some elements. Next, “zip” function is used by passing “list1” and “list2” variables as arguments. This is the main syntax of the “zip” function. You just have to pass lists or other valid ordered iterables as arguments whose elements you want to combine. Lastly, the print statement is used to get the output of the “zipped” variable. After running the code sample mentioned above, you should get the following output:

[('a', 'apple'), ('b', 'ball'), ('c', 'cat')]

Note that the “zip” function returns a “zip” type object and not a list. You have to convert it to an iterable type, as shown in the print statement above.

In simple terms, “zip” function picks up elements of the same index from two lists and combines them as a pair in a tuple. So the 0th element from “list1” is combined with the 0th element of “list2”, the 1st element from “list1” is combined with the 1st element of “list2” and so on. Zip function moves from left to right and the tuple containing paired elements has the same index as the elements stored in them.

Using Zip When Iterables Don’t have Same Number of Elements

In the example stated above, both lists have the equal number of elements. In case you are dealing with some code where both lists don’t have the same number of elements, “zip” function will stop at the last element of the list having the lowest number of elements.

In the example below, “zip” function will stop at the “c” element, regardless of “list2” having one more element.

list1 = ["a", "b", "c"]
list2 = ["apple", "ball", "cat", "doll"]
zipped = zip(list1, list2)
print (list(zipped))

After running the code sample mentioned above, you should get the following output:

[('a', 'apple'), ('b', 'ball'), ('c', 'cat')]

You can Use More than Two Iterables When Using Zip Function

Usually, “zip” function is used to compare two iterable objects. However, you can pass any number of iterables as arguments to the “zip” function. The principle of stopping at the last element of the shortest list will be still applicable.

list1 = ["a", "b", "c"]
list2 = ["apple", "ball", "cat", "doll"]
list3 = ["5", "3"]
zipped = zip(list1, list2, list3)
print (list(zipped))

After running the code sample mentioned above, you should get the following output as result:

[('a', 'apple', '5'), ('b', 'ball', '3')]

Creating Individual Lists from a Zip Type Object

If you already have a “zip” object, you can use it to repopulate individual lists that were earlier used when the zip function was first called on them.

list1 = ["a", "b", "c"]
list2 = ["apple", "ball", "cat", "doll"]
list3 = ["5", "3"]
zipped = zip(list1, list2, list3)
l1, l2, l3 = zip(*zipped)
print (list(l1), list(l2), list(l3))

After running the code sample mentioned above, you should get the following output as result:

['a', 'b'] ['apple', 'ball'] ['5', '3']

In the code sample above, the “zip” object is deflated using “*” operator. Deflated results are then fed into another call to zip function that creates original lists. Note that you may not get all elements back in the original lists if lists of unequal length were used when the “zip” object was created the first time.

Using Zip When You Want to Keep Elements from Longest Iterable

In multiple examples above, you may have observed that the “zip” function by default stops at the last element of the shortest iterable. What if you want it to continue iterating till it reaches the last element of the longest iterable?

In such a case, you will have to use the “zip_longest()” method from Python’s “itertools” module. It works the same as the “zip” function, with one small difference that it stops at the last element of the longest iterable type.

from itertools import zip_longest
list1 = ["a", "b", "c"]
list2 = ["apple", "ball", "cat", "doll"]
list3 = ["5", "3"]
zipped = zip_longest(list1, list2, list3)
print (list(zipped))

After running the code sample mentioned above, you should get the following output as result:

[('a', 'apple', '5'), ('b', 'ball', '3'), ('c', 'cat', None), (None, 'doll', None)]

Missing values are populated as “None” type objects. You can also supply your own value to fill by passing an extra “fillvalue” argument to the “zip_longest” method.

from itertools import zip_longest
list1 = ["a", "b", "c"]
list2 = ["apple", "ball", "cat", "doll"]
list3 = ["5", "3"]
zipped = zip_longest(list1, list2, list3, fillvalue="my_value")
print (list(zipped))

After running the code sample mentioned above, you should get the following output as result:

[('a', 'apple', '5'), ('b', 'ball', '3'), ('c', 'cat', 'my_value'), ('my_value', 'doll', 'my_value')]

Conclusion

Zip function can be emulated using some loops and conditions statements. However, it helps in keeping code organized and cleaner by removing unnecessary verbosity and repetitive statements.

About the author

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.