0

I know how the extend() method works. But when it comes to this program I am not able to figure out the flow of execution. Could

def flatten(arr): resultArr = [] for custItem in arr: if type(custItem) is list: resultArr.extend(flatten(custItem)) else: resultArr.append(custItem) return resultArr print(flatten([[1,2,[3]]])) output- [1,2,3]

7th Aug 2022, 4:12 PM
Levi
Levi - avatar
2 Answers
0
It's just recursion, the code will check for the type of each element of a given list, and if this type is `list`: the function will call itself to work on this new `list` applying the same rule until it does not extend anymore, so it will just consume every list it founds before jumping to the next element.
7th Aug 2022, 5:33 PM
Ervis Meta
Ervis Meta - avatar
0
Ervis Meta - SoloHelper Could u pls explain with an example. It will be really helpful !
8th Aug 2022, 4:33 AM
Levi
Levi - avatar