![]() |
|
[Tut] How to Merge Lists into a List of Tuples? [6 Pythonic Ways] - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Merge Lists into a List of Tuples? [6 Pythonic Ways] (/thread-95660.html) |
[Tut] How to Merge Lists into a List of Tuples? [6 Pythonic Ways] - xSicKxBot - 06-13-2020 How to Merge Lists into a List of Tuples? [6 Pythonic Ways] ![]() The most Pythonic way to merge multiple lists Code: l0, l1, ..., lnCode: iCode: zip()Code: zip(l0, l1, ..., ln)Code: lstCode: zip(*lst)Code: l1 = [1, 2, 3]
l2 = [4, 5, 6]
l = list(zip(l1, l2))
print(l)
# [(1, 4), (2, 5), (3, 6)]The proficient use of Python’s built-in data structures is an integral part of your Python education. This tutorial shows you how you can merge multiple lists into the “column” representation—a list of tuples. By studying these six different ways, you’ll not only understand how to solve this particular problem, you’ll also become a better coder overall. Problem: Given a number of lists Code: l1Code: l2Code: lnExample: Say, you want to merge the following lists Code: l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99]into a list of tuples Code: [(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]This tutorial shows you different ways to merge multiple lists into a list of tuples in Python 3. You can get a quick overview in our interactive Python shell: https://trinket.io/embed/python/3d2e6b11e2 Exercise: Which method needs the least number of characters? Method 1: Zip Function The most Pythonic way that merges multiple lists into a list of tuples is the zip function. It accomplishes this in a single line of code—while being readable, concise, and efficient. The Code: zip()Code: [1, 2, 3]Code: [4, 5, 6]Code: [(1,4), (2,5), (3,6)]Here’s the code solution: Code: l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] print(list(zip(l0, l1, l2)))The output is the following list of tuples: Code: [(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]Note that the return value of the Code: zip()Code: zipCode: list(...)If you have stored the input lists in a single list of lists, the following method is best for you! Method 2: Zip Function with Unpacking You can use the asterisk operator Code: *lstCode: lstCode: zip(lst[0], lst[1], ..., lst[n])Code: zip(*lst)Code: lst = [[0, 'Alice', 4500.00], [1, 'Bob', 6666.66], [2, 'Liz', 9999.99]]
print(list(zip(*lst)))This generates the list of tuples: Code: [(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]I’d consider using the Code: zip()Method 3: List Comprehension List comprehension is a compact way of creating lists. The simple formula is Code: [expression + context]
The example Code: [x for x in range(3)]Code: [0, 1, 2]Related Article: You can read more about list comprehension in my ultimate guide on this blog. You can use a straightforward list comprehension statement Code: [(l0[i], l1[i], l2[i]) for i in range(len(l0))]Code: l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] print([(l0[i], l1[i], l2[i]) for i in range(len(l0))])The output produces the merged list of tuples: Code: [(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]This method is short and efficient. It may not be too readable for you if you’re a beginner coder—but advanced coders usually have no problems understanding this one-liner. If you love to learn everything there is about one-liner Python code snippets, check out my new book “Python One-Liners” (published with San Francisco Publisher NoStarch in 2020). Method 4: Simple Loop Sure, you can skip all the fancy Python and just use a simple loop as well! Here’s how this works: Code: l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = []
for i in range(len(l0)): lst.append((l0[i], l1[i], l2[i]))
print(lst)The output is the merged list of tuples: Code: [(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]Especially coders who come to Python from another programming language such as Go, C++, or Java like this approach. They’re used to writing loops and they can quickly grasp what’s going on in this code snippet. You can visualize the execution of this code snippet in the interactive widget: https://pythontutor.com/iframe-embed.html#code=l0%20%3D%20%5B0,%20'Alice',%204500.00%5D%0Al1%20%3D%20%5B1,%20'Bob',%206666.66%5D%0Al2%20%3D%20%5B2,%20'Liz',%209999.99%5D%0A%0Alst%20%3D%20%5B%5D%0Afor%20i%20in%20range%28len%28l0%29%29%3A%0A%20%20%20%20lst.append%28%28l0%5Bi%5D,%20l1%5Bi%5D,%20l2%5Bi%5D%29%29%0Aprint%28lst%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false Exercise: Click “Next” to see how the memory usage unfolds when running the code. Method 5: Enumerate The Code: enumerate()Code: range(len(l))Code: enumerate()Code: l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = []
for i,x in enumerate(l0): lst.append((x,l1[i],l2[i]))
print(lst)The output is the list of tuples: Code: [(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]Still not satisfied? Let’s have a look at functional programming. Method 6: Map + Lambda With Python’s Code: map()
The result is a Code: mapCode: map()Here’s how you can create a list of tuples from a few given lists: Code: l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = list(map(lambda x, y, z: (x, y, z), l0, l1, l2))
print(lst)The output is the merged list of tuples: Code: [(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]This is both an efficient and readable way to merge multiple lists into a list of tuples. The fact that it isn’t well-known to use the Code: map()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! |