How to Convert a List of Lists Into A Single List

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:

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[0], *lst[1]]

# 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!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!