Write a function to flatten a list. The list contains other lists, strings, or ints. A list such as the example given below is to be flattened:
[[1,'a',['cat'],2],[[[3]],'dog'],4,5]
to produce a flattened list:
[1,'a','cat',2,3,'dog',4,5] (order matters)
I wrote my code as follows and got the required flattened list above. However, I did not score full marks for the question as apparently my code did not work for other test cases. The question did not show me any test cases.Thus I only know that my code works properly for the example given above Could you think of any cases that can show that my code is not correct?
My thinking process: Look through every index element in input list 'aList' by using a for loop. If that element happens to be a str/int, then that element is already flattened and I'll add that into my output flattened list 'new' using append. However, if that index element is still a list, it has not yet be flattened, so I'll do a recursive call 'new.append(aList[n])' so that I now look within list of list ie. aList[0][0] etc. until I find an element that is not a list.
new = []
def flatten(aList):
for n in range(len(aList)):
if type(aList[n]) == type([]):
flatten(aList[n])
else:
new.append(aList[n])
return new
Here, I found a code online that gets me the full marks for the question.
def flatten(aList):
new = []
for i in aList:
if type(i) == type([]):
new.extend(flatten(i))
else:
new.append(i)
return new
It is very similar to my code, with the only difference in the way it calls the recursive function to flatten any nested lists. I directly call my function 'flatten(aList[n])' while the sample answer used 'new.extend(flatten(i)). However, I could not see why my code does not work for all cases. Also, how is using extend going to solve the problem?