Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function to flatten a list. The list contains other lists, strings, or i

ID: 3790396 • Letter: W

Question

Write a function to flatten a list. The list contains other lists, strings, or ints. For example, [[i, ' a', ['cat'], 2], [[[3]], 'dog'], 4, 5] is flattened into [i, 'a', 'cat', 2, 3, 'dog', 4, 5] (order matters). def flatten(aList): aList: a list Returns a copy of a List, which is a flattened version of a List Paste your entire function, including the definition, in the box below. Do not leave any debugging print statements. Note that we ask you to write a function only - you cannot rely on any variables defined outside your function for your code to work correctly.

Explanation / Answer

aList=[[1,[[2]],[[[3]]]],[['4'],{5:5}]]
def flatten(aList):
if aList == []:
return aList
if isinstance(aList[0], list):
return flatten(aList[0]) + flatten(aList[1:])
return aList[:1] + flatten(aList[1:])
print flatten(aList)

Here , we are recursively calling the function flatten, which will take the input as the list and give us an output of the flattened list.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote