How to Convert a List of Lists Into A Single List

Rate this post

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:

## Check results:
# [1, 2, 3, 4]

# [1, 2, 3, 4]

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