pexels munbaik cycling clothing 5851027

Zipped Lists in Python

Working with lists and zipped objects is so easy, and cool as well. You don’t need any initiators or create new instances. Python does all the things required and you only have to work with your desired list.

list_first = [1, 2, 3]
list_second = ['dev', 'ban', 'com']

new_list = list(zip(list_first, list_second))

print(new_list) # 👉 [(1, 'dev'), (2, 'ban'), (3, 'com')]

The Zip function Iterate over several iterables in parallel, producing tuples with an item from each one.

To explain it more, zip() returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.

That being said, it returns an iterator of tuples, so we can iterate over them or convert it to another type.

list_first = [1, 2, 3]
list_second = ['dev', 'ban', 'com']

new_zip_obj = zip(list_first, list_second)

print(new_zip_obj) # 👉 <zip object at 0x7da5213fd7843>

So you can iterate over this zipped object, as below:

list_first = [1, 2, 3]
list_second = ['dev', 'ban', 'com']

new_zip_obj = zip(list_first, list_second)

for tup in new_zip_obj:
    print(tup[0]) # 👇️ prints:
                                 1
                                 2
                                 3
    print(tup[1]) # 👇️ prints:
                                 dev
                                 ban
                                 com

If you want to have a list instead of an object (or iterator of tuples), you can convert the zipped object to a list by doing the same thing we did in the first example.

There isn’t a limitation on the number of elements or lists to use in the zip() function. However, remember that if you feed it with different-sized lists, it will iterate over them for the -least-sized list length- number of times. Let’s see an example:

list_first = [1, 2]
list_second = ['dev', 'ban', 'com']

new_list = list(zip(list_first, list_second))

print(new_list) # 👉 [(1, 'dev'), (2, 'ban')]

As you can see in the above example, it only iterates until the second element, because there isn’t any third element on the list_first so it stops iterating.

Sometimes you may need to print a list of lists from a zipped object, it can be done as the below example:

list_first = [1, 2, 3]
list_second = ['dev', 'ban', 'com']

new_list_of_lists = [list(item) for item in zip(list_first, list_second)]

print(new_list_of_lists) # 👉 [[1, 'dev'], [2, 'ban'], [3, 'com']]

Lists are mutable, meaning they can be manipulated (modified). So you can add or remove items. But tuples are immutable, meaning you can’t change a tuple. Also, tuples are more memory-efficient than lists. So in some cases, you may need a list instead of tuples.