Write a function to flatten a list The list contains other l

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.

Solution

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.

 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 flatte

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site