Skip to content

Commit

Permalink
Flatten any list
Browse files Browse the repository at this point in the history
Flatten the list in python
  • Loading branch information
sumanthkrishna committed Jan 3, 2023
1 parent a66c1e2 commit 21532b1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
18 changes: 18 additions & 0 deletions challenges-flatten-list-1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def flatten(input_list):
# Initialize an empty result list
result = []

# Iterate through the input list
for item in input_list:
# If the item is a list, flatten it and add its elements to the result list
if isinstance(item, list):
result.extend(flatten(item))
# If the item is not a list, add it to the result list
else:
result.append(item)

# Return the result list
return result

#input_list = [[1, 2, 3], [4, 5], [6, 7, 8, [9, 10]]]
#print(flatten(input_list)) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
11 changes: 11 additions & 0 deletions challenges-flatten-list-1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
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]

0 comments on commit 21532b1

Please sign in to comment.