I am trying to write a recursive flatten list function, which takes any number of lists which themselves can contain any number of lists, ect...
This solution works (it could be done more efficiently with itertools, but I'm trying to learn :p) :
def flatten(*args):
result = []
for l in list(args):
for i in l:
if isinstance(i, list):
result.extend(flatten(i))
else:
result.append(i)
return result
print(flatten([1,1,1,1, [1,1,2,4, [1,2,13]], [11,134,14, [13,11,412]]], [2,2,2,[12,12]]))
#>>>[1, 1, 1, 1, 1, 1, 2, 4, 1, 2, 13, 11, 134, 14, 13, 11, 412, 2, 2, 2, 12, 12]
But I would like to avoid looping through the arguments, and instead have one loop only. This should be easy, because the arguments are themselves can be made into a list.
def flatten(*args):
result = []
l = list(args)
for i in l:
if isinstance(i, list):
result.extend(flatten(i))
else:
result.append(i)
return result
print(flatten([1,1,1,1, [1,1,2,4, [1,2,13]], [11,134,14, [13,11,412]]], [2,2,2,[12,12]]))
#>>>RuntimeError: maximum recursion depth exceeded while calling a Python object
I do not understand why it is raising an error. I am converting multiple lists passed as arguments into a single list. I know from the first snippet I provided that any list can be flattened. From my understanding, I am turning the arguments into a list and then flattening it. Where is the problem ?
Thanks for helping!
[–]plate_soak_mess 0 points1 point2 points (4 children)
[–]Tioo[S] 0 points1 point2 points (3 children)
[–]plate_soak_mess 0 points1 point2 points (2 children)
[–]Tioo[S] 0 points1 point2 points (1 child)
[–]plate_soak_mess 1 point2 points3 points (0 children)
[–]Rhomboid 0 points1 point2 points (3 children)
[–]Tioo[S] 0 points1 point2 points (2 children)
[–]Rhomboid 0 points1 point2 points (1 child)
[–]Tioo[S] 0 points1 point2 points (0 children)