-2

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]
Nihal
  • 5,262
  • 7
  • 23
  • 41
  • Take one of the [answers here](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) and add your own type checking. If something goes wrong, post a question asking for help. – Selcuk Feb 22 '19 at 05:47
  • (4,5,6) should be [4,5,6] if you want expected result – PySaad Feb 22 '19 at 05:48

3 Answers3

0
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]
ycx
  • 3,155
  • 3
  • 14
  • 26
0

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]
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
0

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]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • This only works for 1 layer of nesting though. But it does fit the question's criteria. – ycx Feb 22 '19 at 08:07