![]() |
|
[Tut] Convert Tuple to List | The Most Pythonic Way - 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] Convert Tuple to List | The Most Pythonic Way (/thread-95865.html) |
[Tut] Convert Tuple to List | The Most Pythonic Way - xSicKxBot - 06-24-2020 Convert Tuple to List | The Most Pythonic Way Answer: The simplest, most straightforward, and most readable way to convert a tuple to a list is Python’s built-in Code: list(tuple)Converting a tuple to a list seems trivial, I know. But keep reading and I’ll show you surprising ways of handling this problem. I guarantee that you’ll learn a lot of valuable things from the 3-5 minutes you’ll spend reading this tutorial! ![]() Problem: Given a tuple of elements. Create a new list with the same elements—thereby converting the tuple to a list. Example: You have the following tuple. Code: t = (1, 2, 3)You want to create a new list data structure that contains the same integer elements: Code: [1, 2, 3]Let’s have a look at the different ways to convert a tuple to a list—and discuss which is the most Pythonic way in which circumstance. You can get a quick overview in the following interactive code shell. Explanations for each method follow after that: https://trinket.io/embed/python/dcf132285d Exercise: Run the code. Skim over each method—which one do you like most? Do you understand each of them? Let’s dive into the six methods. Method 1: List Constructor The simplest, most straightforward, and most readable way to convert a tuple to a list is Python’s built-in Code: list(iterable)![]() Here’s an example: Code: # Method 1: list() constructor
t = (1, 2, 3)
lst = list(t)
print(lst)
# [1, 2, 3]This is the most Pythonic way if a flatconversion of a single tuple to a list is all you need. But what if you want to convert multiple tuples to a single list? Method 2: Unpacking There’s an alternative that works for one or more tuples to convert one or more tuples into a list. This method is equally efficient and it takes less characters than Method 1 (at the costs of readabilityfor beginner coders). Sounds interesting? Let’s dive into unpacking and the asterisk operator! The asterisk operator Code: *Here’s how it works to unpack all elements of a tuple into an enclosing list—thereby converting the original tuple to a new list. Code: # Method 2: Unpacking
t = (1, 2, 3)
lst = [*t]
print(lst)
# [1, 2, 3]You unpack all elements in the tuple Code: tCode: [*t]Code: list(...)Method 3: Unpacking to Convert Multiple Tuples to a Single List Let’s have a look at how you’d create a list from multiple tuples: Code: # Method 3: Unpacking Multiple Tuples
t1 = (1, 2, 3)
t2 = (4, 5, 6)
lst = [*t1, *t2]
print(lst)
# [1, 2, 3, 4, 5, 6]The expression Code: [*t1, *t2]Code: t1Code: t2Method 4: Generator Expression to Convert Multiple Tuples to List If you have multiple tuples stored in a list of lists (or list of tuples) and you want to convert them to a single list, you can use a short generator expression statement to go over all inner tuples and over all elements of each inner tuple. Then, you place each of those elements into the list structure: Code: # Method 4: Generator Expression
ts = ((1, 2), (3, 4), (5, 6, 7))
lst = [x for t in ts for x in t]
print(lst)
# [1, 2, 3, 4, 5, 6, 7]This is the most Pythonic way to convert a list of tuples (or tuple of tuples) to a tuple. It’s short and efficient and readable. You don’t create any helper data structure that takes space in memory. But what if you want to save a few more characters? Method 5: Generator Expression + Unpacking Okay, you shouldn’t do this last method using the asterisk operator—it’s unreadable—but I couldn’t help including it here: Code: # Method 5: Generator Expression + Unpacking
t = ((1, 2), (3, 4), (5, 6, 7))
lst = [*(x for t in ts for x in t)]
print(lst)
# [1, 2, 3, 4, 5, 6, 7]Rather than using the Code: list(...)Code: [...]Method 6: Simple For Loop Let’s end this article by showing the simple thing—using a for loop. Doing simple things is an excellent idea in coding. And, while the problem is more elegantly solved in Method 1 (using the Code: list()Code: # Method 6: Simple For Loop
t = (1, 2, 3, 4)
lst = []
for x in t: lst.append(x)
print(lst)
# [1, 2, 3, 4]To understand how the code works, you can visualize its execution in the interactive memory visualizer: https://pythontutor.com/iframe-embed.html#code=%23%20Method%206%3A%20Simple%20For%20Loop%0At%20%3D%20%281,%202,%203,%204%29%0Alst%20%3D%20%5B%5D%0Afor%20x%20in%20t%3A%0A%20%20%20%20lst.append%28x%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: How often is the loop condition checked? You will see such a simple conversion method in code bases of Python beginners and programmers who switch to Python coming from other programming languages such as Java or C++. It’s readable but it lacks conciseness. I hope you liked the article! Please find related articles here: Related articles: If you want to boost your Python skills, I’ve created an online academy that’s entirely based on email (and it’s free). Feel free to join our large community of ambitious Python coders and download your free Python resources (PDF cheat sheets). 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! |