26.5k views
0 votes
Write the recursive function flat(aList) that takes a possibly deep list and flattens it. The function should not mutate the original list. Hint: you can check if something is a list by using the built-in functions type() or isinstance [3, [[5, 2, 6, [4]] >>>X flat (x) [3, 5, 2, 6, 4] >>>X [3, [[5, 2, 6, [4]]

User Cyngus
by
5.1k points

1 Answer

5 votes

Answer:

There is an attachment below

Step-by-step explanation:

CODE

def flat(aList):

if aList == []:

return aList

if isinstance(aList[0], list):

return flat(aList[0]) + flat(aList[1:])

return aList[:1] + flat(aList[1:])

x = [3, [[5, 2]], 6, [4]]

print(x)

print(flat(x))

Write the recursive function flat(aList) that takes a possibly deep list and flattens-example-1
User Dick
by
5.2k points