Zip with list output instead of tuple in Python

avatar

Borislav Hadzhiev

Last updated: Jun 30, 2022

banner

Photo from Unsplash

Zip with list output instead of tuple in Python #

To get list output instead of tuple from the zip() function:

  1. Use a list comprehension to iterate over the zip object.
  2. Use the list() class to convert each tuple to a list.
  3. The new list will contain nested lists instead of tuples.
main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] list_of_lists = [list(tup) for tup in zip(list_1, list_2)] # 👇️ [[1, 'a'], [2, 'b'], [3, 'c']] print(list_of_lists)

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

By default, the zip function returns an iterator of tuples.

main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] # 👇️ [(1, 'a'), (2, 'b'), (3, 'c')] print(list(zip(list_1, list_2)))

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.

main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] list_of_lists = [list(tup) for tup in zip(list_1, list_2)] # 👇️ [[1, 'a'], [2, 'b'], [3, 'c']] print(list_of_lists)

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

Alternatively, you can use the map() function.

To get list output instead of tuple from the zip() function:

  1. Use the map() function to pass each tuple in the zip object to the list() class.
  2. Use the list() class to convert the map object to a list.
main.py
list_1 = [1, 2, 3] list_2 = ['a', 'b', 'c'] list_of_lists = list(map(list, zip(list_1, list_2))) # 👇️ [[1, 'a'], [2, 'b'], [3, 'c']] print(list_of_lists)

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The map() function passes each tuple in the zip object to the list() class.

The map() function returns a map object, so we had to use the list() class to convert it to a list.

Which approach you pick is a matter of personal preference. I'd go with using a list comprehension because I find it more explicit and easier to read.

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.