Python Principles
Python Q&A

How do I flatten a list in Python?


Let's say you want to turn this list:

xs = [[1, 2], [3, 4]]

Into this flattened list:

flattened = [1, 2, 3, 4]

Assuming that you have a list of lists, you can iterate over each nested list, then over each element in that nested list. This way you can access each element at a time. Then append the element to a new, flattened list. Like this:

xs = [[1, 2], [3, 4]]
flattened = []
for nested_list in xs:
    for element in nested_list: