Say, you want to convert a list of lists
lst=[[1, 2], [3, 4]] into a single list
[1, 2, 3, 4]. How to achieve this? There are different options:
- List comprehension
[x for l in lst for x in l]assuming you have a list of lists
[*lst, *lst]assuming you have a list of two lists
- Using the
extend()method of Python lists to extend all lists in the list of lists.
Find examples of all three methods in the following code snippet:
lst = [[1, 2], [3, 4]] # Method 1: List Comprehension flat_1 = [x for l in lst for x in l] # Method 2: Unpacking flat_2 = [*lst, *lst] # Method 3: Extend Method flat_3 =  for l in lst: flat_3.extend(l) ## Check results: print(flat_1) # [1, 2, 3, 4] print(flat_2) # [1, 2, 3, 4] print(flat_3) # [1, 2, 3, 4]
Due its simplicity and efficiency, the first list comprehension method is superior to the other two methods.
You can check out these methods yourself in our interactive code shell:
Do you need to dive even deeper into this code snippet? Try the Python teacher code execution to see the memory objects created by this code:
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.