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.

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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.88805634,"math_prob":0.91720563,"size":4650,"snap":"2021-43-2021-49","text_gpt3_token_len":1112,"char_repetition_ratio":0.1476539,"word_repetition_ratio":0.20676203,"special_character_ratio":0.24924731,"punctuation_ratio":0.1146789,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97279793,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-11-29T03:25:17Z\",\"WARC-Record-ID\":\"<urn:uuid:aca9318d-2ad4-4ddb-b4d6-dcee264d2a90>\",\"Content-Length\":\"127751\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:32f1a686-2d8b-42b8-bd53-9ec15f95634b>\",\"WARC-Concurrent-To\":\"<urn:uuid:fe31e226-85f5-4438-8514-d05be509151d>\",\"WARC-IP-Address\":\"104.21.58.234\",\"WARC-Target-URI\":\"https://linuxhint.com/use-zip-function-python/\",\"WARC-Payload-Digest\":\"sha1:DAWBAVY7TETQG4B3QHN33TJDVDJ5ACMG\",\"WARC-Block-Digest\":\"sha1:RKDDCWMEVD72ELL5BROFZAXJULGCMPA5\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-49/CC-MAIN-2021-49_segments_1637964358685.55_warc_CC-MAIN-20211129014336-20211129044336-00321.warc.gz\"}"}