Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Zip With List Output Instead of Tuple | Most Pythonic Way

#1
Zip With List Output Instead of Tuple | Most Pythonic Way

Short answer: Per default, the zip() function returns a zip object of tuples. To obtain a list of lists as an output, use the list comprehension statement [list(x) for x in zip(l1, l2)] that converts each tuple to a list and stores the converted lists in a new nested list object.

Intermediate Python coders know the zip() function. But if you’re like me, you’ve often cursed the output of the zip function: first of all, it’s a zip object (and not a list), and, second, the individual zipped elements are tuples. But what if you need a list of lists as output? This article will show you the most Pythonic way of doing this.



Problem: Given a number of lists l1, l2, .... How ot zip the i-th elements of those lists together and obtain a list of lists?

Example: Given two lists [1, 2, 3, 4] and ['Alice', 'Bob', 'Ann', 'Liz'] and you want the list of lists [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']].

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz']
# ... calculate result ...
# Output: [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

Here’s a quick overview of our solutions:

Exercise: Create a new list l3 and change the four methods to zip together all three lists (instead of only two).

Method 1: Generator Expression


The first method uses a generator expression and converts the resulting iterable to a list using the list() constructor.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 1
zipped = list(list(x) for x in zip(l1, l2)) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

This is efficient but not the most concise way of accomplishing this task.

Method 2: List Comprehension


A better way is to use list comprehension which is like a generator expression but it creates a list directly without the need to convert an iterable to a list (as in Method 1).

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 2:
zipped = [list(x) for x in zip(l1, l2)] print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

Method 3: For Loop and Zip


Coders who don’t like list comprehension and generator expressions (or, who don’t understand these beautiful Python features) often use a simple for loop. In the loop body, you convert each tuple in the zip object to a list and append this list to the nested list zipped.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 3:
zipped = []
for t in zip(l1, l2): zipped.append(list(t)) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

This method is readable but less concise.

Method 4: For Loop and Indexing


This method is often used by coders who know neither the zip() method, nor list comprehension, nor generator expressions: loop over all indices and append a new list obtained by grouping the i-th elements to the list.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 4:
zipped = []
for i in range(len(l1)): zipped.append([l1[i], l2[i]]) print(zipped)
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

However, this method is least Pythonic, lengthy, and it works only for equally-sized lists.

Exercise: What happens if the first list has more elements than the second list?

Method 5: Zip() + Map() + List()


A functional way of solving this problem is the map() function that applies a function to each element of an iterable and returns a map object. You can pass the list() constructor to the map() function to convert each tuple in the zip object to a list. You can then convert the map object to a list.

l1 = [1, 2, 3, 4]
l2 = ['Alice', 'Bob', 'Ann', 'Liz'] # Method 5
print(list(map(list,zip(l1, l2))))
# [[1, 'Alice'], [2, 'Bob'], [3, 'Ann'], [4, 'Liz']]

I don’t recommend this method because functional programming may be difficult to understand for many beginner coders. Guido van Rossum, the creator of Python, disliked functional programming as well.

Discussion


The most Pythonic way to create a list of lists by zipping together multiple lists is the list comprehension statement [list(x) for x in zip(l1, l2)]. List comprehension is fast, efficient, concise, and readable. You can also extend it to the general case by adding more lists to the zip function: [list(x) for x in zip(l1, l2, l3, ..., ln)]. The zip() function is also robust against lists of different lengths. In this case, the elements up to the maximal index of the shortest list are zipped.

Where to Go From Here?


Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2020/07/...honic-way/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] The Most Pythonic Way to Get N Largest and Smallest List Elements xSicKxBot 0 2,050 09-01-2023, 03:23 AM
Last Post: xSicKxBot
  [Tut] Python IndexError: Tuple Index Out of Range [Easy Fix] xSicKxBot 0 1,950 08-22-2023, 09:07 AM
Last Post: xSicKxBot
  [Tut] Python Tuple Concatenation: A Simple Illustrated Guide xSicKxBot 0 1,938 08-21-2023, 10:25 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,694 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Easiest Way to Convert List of Hex Strings to List of Integers xSicKxBot 0 1,458 11-25-2022, 11:54 AM
Last Post: xSicKxBot
  [Tut] Python Find Shortest List in List xSicKxBot 0 1,372 09-25-2022, 03:42 AM
Last Post: xSicKxBot
  [Tut] Python Find Longest List in List xSicKxBot 0 1,302 09-23-2022, 02:19 PM
Last Post: xSicKxBot
  [Tut] Python Set to Tuple | Tuple to Set | 3 Easy Ways xSicKxBot 0 1,193 09-21-2022, 10:33 PM
Last Post: xSicKxBot
  [Tut] How to Create a Python Tuple of Size n? xSicKxBot 0 1,211 08-26-2022, 10:02 AM
Last Post: xSicKxBot
  [Tut] Python Tuple Comprehension Doesn’t Exist – Use This Instead xSicKxBot 0 1,147 06-04-2022, 12:46 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016