gaut
gaut

Reputation: 5958

Flatten last layer of nested list using comprehension

How can I flatten the last layer of a nested list?

lista = [['a'],['b']]
listb = [['c']]
nested = [lista, listb]

# [[['a'], ['b']], [['c']]]
# how to get [['a', 'b'], ['c']]?

[[x for x in y] for y in nested]
# gives [[['a'], ['b']], [['c']]]

I tried with unpacking but it is disallowed in list comprehension.

For more context, the reason the last elements are always 1-element list is that I get this result by using:

[myfunc(x) for x in y for y in other_nested_list]

Upvotes: 0

Views: 96

Answers (4)

Deepak Tripathi
Deepak Tripathi

Reputation: 3233

You can create your own function that will run recursively where you will tell at which level do you want to unpack your list

nested = [[['a'], ['b']], [['c']]]
def unstack(l, level):
    if level == 1:
        return l[0]
    res = []
    for i in l:
        if isinstance(i, list):
            res.append(unstack(i, level-1))
        else:
            res.append(i)
    return res

unstack(nested, 3)  # [['a', 'b'], ['c']]

It will work for each nested layer, you have to provide the level till which you want to unstack this list.

Upvotes: 1

Dmitriy Neledva
Dmitriy Neledva

Reputation: 864

lista = [['a'],['b']]
listb = [['c']]
nested = [lista, listb]

# [[['a'], ['b']], [['c']]]
# how to get [['a', 'b'], ['c']]?

print([[x for x in y] for y in nested])
# gives [[['a'], ['b']], [['c']]]


#simple solution:
print([[x[0] for x in y] for y in nested])
# gives [['a', 'b'], ['c']]


#solution with itertools (it will work to list with multiple items inside it too):
import itertools
print([list(itertools.chain.from_iterable([x for x in y])) for y in nested])
# gives [['a', 'b'], ['c']]


#solution with `unlist()` (== with itertools still):
def unlist(lst):
    return list(itertools.chain.from_iterable(lst))

print([unlist([x for x in y]) for y in nested])
# gives [['a', 'b'], ['c']]

Upvotes: 3

Alexander
Alexander

Reputation: 17291

You can use list comprehension:

lista = ['a','b']
listb = ['c']
nested = [[lista], [listb]]
listc = [j for i in nested for j in i]
print(listc)

or you can use itertools

import itertools
lista = ['a','b']
listb = ['c']
nested = [[lista], [listb]]
listc = list(itertools.chain.from_iterable(nested))
print(listc)

output:

[['a', 'b'], ['c']]
[['a', 'b'], ['c']]

update

you can use both examples from above and then

lista = [[['a'], ['b']], [['c']]]
listb = [j for i in lista for j in i]
listc = [listb[0] + listb[1], listb[2]]
print(listc)

output

[['a', 'b'], ['c']]

Upvotes: 1

PangolinPaws
PangolinPaws

Reputation: 717

List comprehension isn't needed, so if it's not a fixed requirement for some other reason, you can just add the lists together with +:

lista = ['a','b']
listb = ['c']
nested = [lista] + [listb]

print(nested)

Output:

[['a', 'b'], ['c']]

Upvotes: 1

Related Questions