-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatten.py
35 lines (30 loc) · 836 Bytes
/
flatten.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 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]
#My naive solution
def flatten(l1):
newlist = []
for i in l1:
for x in i:
newlist.append(x)
return newlist
#Python principles
# naive solution
def flatten(outer_list):
result = []
for inner_list in outer_list:
for item in inner_list:
result.append(item)
return result
# solution with nested list comprehensions
# (can be put on a single line for conciseness)
def flatten(outer_list):
return [
item
for inner_list in outer_list
for item in inner_list
]