DEV Community

Cover image for Python challenge_9
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on


Python challenge_9

Flatten a list

level of challenge 3/10

  • 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]


Start by defining an empty list as the result:

result = []

Then use a nested for loop to fill up the result.

# My solution

def flatten(out_list):
    new_list = [] 
    for in_list in out_list:
        for item in in_list:
    return new_list
print(flatten([[1, 2], [3, 4], [5, 6], [7, 8]]))
Enter fullscreen mode Exit fullscreen mode
# Another Solution

def flatten(outer_list):
  return [
    for inner_list in outer_list
    for item in inner_list

Enter fullscreen mode Exit fullscreen mode

Add your solution in the comment :)

Top comments (0)