Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Flatten a list

Write a function that takes a list of lists and flattens it into a one-dimensional list.

Name your function flatten. It should take a single parameter and return a list.

For example, calling:

flatten([[1, 2], [3, 4]])

Should return the list:

[1, 2, 3, 4]


==== SOLUTION ====

 Here's how you can do it using a traditional loop:

“`python
def flatten(list_of_lists):
flattened_list = []
for sublist in list_of_lists:
for item in sublist:
flattened_list.append(item)
return flattened_list

# Test the function
print(flatten([[1, 2], [3, 4]])) # Output: [1, 2, 3, 4]
“`

Explanation:

1. `def flatten(list_of_lists):`: This line defines a function named `flatten` that takes a single parameter `list_of_lists`, which is a list of lists.

2. `flattened_list = []`: This line initializes an empty list `flattened_list` to store the flattened version of the input list of lists.

3. `for sublist in list_of_lists:`: This loop iterates over each sublist in the input `list_of_lists`.

4. `for item in sublist:`: This nested loop iterates over each item in the current sublist.

5. `flattened_list.append(item)`: Inside the nested loop, this line appends each item from the sublists into the `flattened_list`.

6. Finally, the function returns the `flattened_list`, which contains all the items from the nested lists concatenated into a single list.

 



Join the conversation