2

Is there any quick ways to untangle elements in a list? For example: Given

list = [[1,2,3],[4,2],2,1,3]

We'll have:

list = [1,2,3,4,2,2,1,3]
Thuan Hieu
  • 33
  • 1
  • 1
  • 5

2 Answers2

4

You can use a list comprehension after casting any non-list values as lists:

l = [[1,2,3],[4,2],2,1,3]
new_l = [i for b in map(lambda x:[x] if not isinstance(x, list) else x, l) for i in b]

Output:

[1, 2, 3, 4, 2, 2, 1, 3]

Edit: for nested levels, you can use recursion with a generator expression:

def flatten(d):
 v = [[i] if not isinstance(i, list) else flatten(i) for i in d]
 return [i for b in v for i in b]

print(flatten(l) Output:

[1, 2, 3, 4, 2, 2, 1, 3]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

You can use itertool.chain for this:

from itertools import chain

lst = [[1,2,3],[4,2],2,1,3]

res = list(chain.from_iterable(i if isinstance(i, list) else [i] for i in lst))

# [1, 2, 3, 4, 2, 2, 1, 3]
jpp
  • 159,742
  • 34
  • 281
  • 339