2

How would you convert a list like this :

["foo",["banana","apple"], "banana", ["peaches","grapes"]]

into

["foo","banana","apple", "banana", "peaches",'grapes"]

I tried:

flat_list = [item for sublist in regular_list for item in sublist]
d.b
  • 32,245
  • 6
  • 36
  • 77
star_it8293
  • 399
  • 3
  • 12

3 Answers3

3

If the maximum depth of nesting is not too large, you can use recursion to flatten even deeper amount of nesting:

def flatten(a):
    if not isinstance(a, list):
        yield a
        return
    for x in a:
        yield from flatten(x)

regular_list = ["foo",[[[["banana",[["apple"]]]]]], [[[["banana"]]]], ["peaches","grapes"]]
flat_list = list(flatten(regular_list))
print(flat_list)

Output

['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']
matias
  • 340
  • 2
  • 9
2

One approach using a nested list comprehension could be to check if each element is a list, and convert it to a list type otherwise:

regular_list = ["foo",["banana","apple"], "banana", ["peaches","grapes"]]


flat_list = [item for sublist in regular_list
             for item in (sublist if isinstance(sublist, list) else [sublist])]

print(flat_list)

Result:

['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
1
arr = ["foo", ["banana", "apple"], "banana", ["peaches", "grapes"]]

ans = []
for el in arr:
    ans.extend(el) if isinstance(el, list) else ans.append(el)
ans
# ['foo', 'banana', 'apple', 'banana', 'peaches', 'grapes']
d.b
  • 32,245
  • 6
  • 36
  • 77
  • `ans.extend(el) if isinstance(el, list) else ans.append(el)` doesn't evaluate to anything other than `None`, so using an expression is pointless, just use a regular if-else *statement* instead of an expression – juanpa.arrivillaga Jun 02 '22 at 20:58
  • @juanpa.arrivillaga, why does it have to evaluate to anything if I haven't assigned it to a variable? – d.b Jun 02 '22 at 21:04