1

How would you flatten the list l:

  l = [1,2,[3,4,5],6,7]

giving the list:

  [1,2,3,4,5,6,7]

This is not the same as flattening:

  l = [[1],[2],[3,4,5],[6],[7]]

as addressed here:

How to make a flat list out of list of lists

where l in this case contains only a list of lists of int.

Baz
  • 12,713
  • 38
  • 145
  • 268
  • @Barmar I dont think this is a duplicate of the question you link to as that list doesnt pertain to a list of mixed types. – Baz Sep 04 '19 at 16:33

2 Answers2

1
l = [1,2,[3,4,5],6,7] result =[] 

result = []

def flatten(lst):   
  for item in lst:
    if isinstance(item,list):
      flatten(item)
    else:
      result.append(item)

flatten(l)

print(result)
Fuji Komalan
  • 1,979
  • 16
  • 25
1

You can use recursion to solve this problem, which will work with any iterator:

l = [1, 2, [3, 4, 5], 6, 7, (8, 9, 10), set([11, 12]), 13, 14]

def flat(l):
    if not l:
        return l
    f = l[0]
    try:
        p = [i for i in f]
    except TypeError:
        # f is not iterable, so put it in a list.
        p = [f]
    return p + flat(l[1:])

print(flat(l))

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
chepner
  • 497,756
  • 71
  • 530
  • 681
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Any way of testing if container type versus value type while iterating. For example if the list contained: [1,2,3.5, (4.5,5),[6,7,8],set(9,10)]. This should be flattened to: [1,2,3.5,4.5,5,6,7,8,9,10] – Baz Sep 04 '19 at 16:45
  • 1
    @Baz Check the additional code I added in the function. – DjaouadNM Sep 04 '19 at 16:54