TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.8K subscribers
Post #9232 1.56K
A bit of #Python basics. Day 8 - Flatten a nested list

I'll show you three (3) ways to flatten a two-dimensional list. The first method uses a for loop, the second uses the itertools module, and the third uses list comprehension.

⚙️ Using a for loop:

For this method, we use a nested for loop. The outer loop iterates over the inner lists, and the inner loop accesses the elements in the inner lists.

# In [19]:
list1 = [[1, 2, 3],[4, 5, 6]]

newlist = []
for list2 in list1:
    for j in list2:
        newlist.append(j)

print(newlist)


[1, 2, 3, 4, 5, 6]

⚙️ Using the itertools module:

The itertools.chain.from_iterable() function from the itertools module can be used to flatten a nested list. This method may not be suitable for deeply nested lists.

# In [20]:
import itertools

list1 = [[1, 2, 3],[4, 5, 6]]

flat_list = list(itertools.chain.from_iterable(list1))
print(flat_list)


[1, 2, 3, 4, 5, 6]

You can see that the nested loop has been flattened.

⚙️ Using list comprehension

If you don't want to import itertools or write a regular for loop, you can simply use list comprehension.

# In [21]:
list1 = [[1, 2, 3], [4, 5, 6]]

flat_list = [i for j in list1 for i in j]
print(flat_list)


[1, 2, 3, 4, 5, 6]

List comprehension is well suited for moderately nested lists. For deeply nested lists, it is not suitable, as the code becomes harder to read.

⚙️ Using a generator function

You can create a generator function that yields elements from the nested list, and then convert the generator into a list.

# In [22]:
def flatten_generator(nested_list):
    for sublist in nested_list:
        for item in sublist:
            yield item

list1 = [[1, 2, 3], [4, 5, 6]]

flat_list = list(flatten_generator(list1))
flat_list


Out[22]: [1, 2, 3, 4, 5, 6]

The generator method is suitable for flattening large or deeply nested lists. This is because generators are memory-efficient.

👉 https://t.me/DataScience4
  • ❤ 7
More from @pythonre
  1. Oct 10, 2026📚 Download 10 Python books for FREE: 1. Think Python — O’Reilly https://t.co/X7y3pX68IW 2…
  2. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  3. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  4. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
  5. Oct 6, 2026Post #9851
  6. Oct 6, 2026Python For Beginners Course In-Depth Python: A Comprehensive Introduction to Fundamental P…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →