Lists can contain other lists as elements For example the li

Lists can contain other lists as elements. For example the list HAIRY=[1,2,[3,4,[5,[6,7.8],[9,10]],11,[12,[13,14],[15,16]]]] contains several lists containing other lists -- ie it is a \"multilevel\" list. Write a function flatten(L) which takes a possibly multi-level list L as an argument and returns a new list with the same elements in the same overall order as L but with only one level. For example, flatten(HAIRY) would return the list [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

Solution

Please find the required program along with its output. Please see the comments against each line to understand the step.

def flatten(L): #recursive function to flatten a list
for element in L: #iterate through each element of a list
if not isinstance(element, list): # if the element is not a list,
yield element # just return the element
else: #if the element is a list, then recursivley call the flatten fucntion on the sub list, and return each element individually
for x in flatten(element):
yield x
  
print \"Flattened list elements are: \"   
for x in flatten([1,2,[3,4,[5,[6,7,8],[9,10]],11,[12,[13,14],[15,16]]]]):
print x, #print the flatten list elements

----------------------------------------

OUTPUT :

Flattened list elements are:                                                                                                                                                                                  

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Lists can contain other lists as elements. For example the list HAIRY=[1,2,[3,4,[5,[6,7.8],[9,10]],11,[12,[13,14],[15,16]]]] contains several lists containing o

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site