How to flatten a nested list that contains tuples without removing the tuples? example:
flatten([1,2,3,(4,5,6),[7,8,9]])
[1, 2, 3, (4, 5, 6),7,8,9]
How to flatten a nested list that contains tuples without removing the tuples? example:
flatten([1,2,3,(4,5,6),[7,8,9]])
[1, 2, 3, (4, 5, 6),7,8,9]
def flatten(arr):
if not isinstance(arr, list):
return arr
else:
output = []
for sy in arr:
if isinstance(sy, list):
temp = flatten(sy)
for py in temp:
output.append(py)
else:
output.append(sy)
return output
print (flatten([1,2,3,(4,5,6),[7,8,9]]))
#[1, 2, 3, (4, 5, 6), 7, 8, 9]
Here a try :
f = lambda *n: (e for a in n
for e in (f(*a) if isinstance(a, (list)) else (a,)))
print(list(f([1,2,3,(4,5,6),[7,8,9]])))
# [1, 2, 3, (4, 5, 6), 7, 8, 9]
Why not simple loops:
>>> L = [1,2,3,(4,5,6),[7,8,9]]
>>> L2 = []
>>> for i in L:
if isinstance(i,list):
L2.extend(i)
else:
L2.append(i)
>>> L2
[1, 2, 3, (4, 5, 6), 7, 8, 9]
>>>