Skip to content

Python zip two lists | Example code

  • by

Using the zip() method you can merge the two lists in Python. The zip() takes a variable number of arguments. zip(one, two, three) will work, and so on for as many arguments as you wish to pass in.

list(zip(a, b))

Note: in python 3.0 zip returns a zip object. You can get a list out of it by calling list(zip(a, b)).

How to zip two lists in Python Example

Simple Python zip two lists example code. First Create a zip object then Convert the zip to a list.

Use the list() method to convert the zip object to a list containing zipped pairs from the original two lists.

list1 = [11, 22, 33]

list2 = [10, 20, 30]

a_zip = zip(list1, list2)

print(list(a_zip))

Output:

Python zip two lists

Iterating through two lists in parallel using zip()

The zip returns a list of tuples. Using iteration will get the first element of both lists, then the second element of both lists, then the third, etc.

a = [1, 2, 3]

b = [10, 20, 30]

for i, j in zip(a, b):
    print(i, j)

Output:

1 10
2 20
3 30

Create a dictionary by passing the output of zip to dict

key = ['a', 'b', 'c']

v = [10, 20, 30]

print(dict(zip(key, v)))

Output: {‘a’: 10, ‘b’: 20, ‘c’: 30}

Do comment if you have any doubts and suggestions on this Python zip tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading