Print a zipped list in Python


Borislav Hadzhiev

Last updated: Sep 12, 2022


Photo from Unsplash

Print a zipped list in Python #

To print a zipped list:

  1. Use the zip() function to get an iterator of tuples.
  2. Use the list() class to convert the iterator to a list.
  3. Use the print() function to print the list.
list_1 = [1, 2, 3] list_2 = ['bobby', 'hadz', 'com'] my_list = list(zip(list_1, list_2)) # 👇️ [(1, 'bobby'), (2, 'hadz'), (3, 'com')] print(my_list)

The zip function iterates over several iterables in parallel and produces tuples with an item from each iterable.

The zip function returns an iterator of tuples.
list_1 = [1, 2, 3] list_2 = ['bobby', 'hadz', 'com'] zip_obj = zip(list_1, list_2) # 👇️ <zip object at 0x7fb7621fe080> print(zip_obj)

This is why we had to use the list() class to convert the zip object to a list.
list_1 = [1, 2, 3] list_2 = ['bobby', 'hadz', 'com'] zip_obj = list(zip(list_1, list_2)) # 👇️ [(1, 'bobby'), (2, 'hadz'), (3, 'com')] print(zip_obj)

You can use the zip() function with as many iterables as necessary.
list_1 = [1, 2, 3] list_2 = ['bobby', 'hadz', 'com'] list_3 = ['one', 'two', 'three'] zip_obj = list(zip(list_1, list_2, list_3)) # 👇️ [(1, 'bobby', 'one'), (2, 'hadz', 'two'), (3, 'com', 'three')] print(zip_obj)

The zip() function returns a zip object of tuples.

Something you might often have to do is convert the tuples in the zip object to lists.
list_1 = [1, 2, 3] list_2 = ['bobby', 'hadz', 'com'] list_of_lists = [list(tup) for tup in zip(list_1, list_2)] # 👇️ [[1, 'bobby'], [2, 'hadz'], [3, 'com']] print(list_of_lists)

We used a list comprehension to iterate over the zip object.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we used the list() class to convert the tuple to a list.

The list class takes an iterable and returns a list object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.