Nov-24-2018, 07:25 PM
There are different solutions, but I prefer to use a closure and a helper function like so
def flatten(to_flatten): result = [] def helper(nested_list): for i in nested_list: if type(i) != list: result.append(i) else: helper(i) return result return helper(to_flatten)Alternatively, you could have a second parameter which defaults to None, and you have have logic which creates the
result
variable when that parameter is None and then provide it for the recursive calls. I prefer the method I've coded here because it does not change the interface given to clients of the code, who might accidentally provide a second parameter (or who might notice it and wonder).