Skip to content

Commit 87f4077

Browse files
authored
Add files via upload
1 parent ca9255a commit 87f4077

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

flatten_list.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Python Flatten Nested Lists
2+
# (c) Joe James 2023
3+
4+
# list comprehension method
5+
def flatten1 (myList):
6+
return [i for j in myList for i in j]
7+
8+
# recursive method
9+
def flatten2 (myList):
10+
flatList = []
11+
for item in myList:
12+
if isinstance(item, list):
13+
flatList.extend(flatten2(item))
14+
else:
15+
flatList.append(item)
16+
return flatList
17+
18+
list1 = [[0], [1, 2], [3, [4, 5]], [6], [7]]
19+
list2 = [0, [1, 2], [3, [4, 5]], [6], 7]
20+
21+
print("flatten1(list1): ", flatten1(list1)) # works, but only flattens 1 layer of sublists
22+
# print(flatten1(list2)) # error - can't work with list of ints and sublists of ints
23+
24+
print("flatten2(list1): ", flatten2(list1))
25+
print("flatten2(list2): ", flatten2(list2))
26+
27+

0 commit comments

Comments
 (0)