Alright guys so I have a little problem with a nested list.

so here is my list:

a = [[1,2,3], [4,5,6], [7,8,9]]
#I know that I can  do for example a[0][0] and that will return the first value in the first nested list but I don't know how to extract them all without having to do that for every one of them. In the end what I want is a new list like this:
a = [1,2,3,4,5,6,7,8,9]

Is there a way to do this? I already tried Google but it didn't help.

Recommended Answers

All 4 Replies

There are many ways to flatten a list. Here are two. I'm sure a Google would come up with many more.

a = [[1,2,3], [4,5,6], [7,8,9]]
b = [num for sublist in a for num in sublist]
print b

import itertools
c = itertools.chain(*a)
print list(c)

How about this:

>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> new_a = []
>>> for each_a in a:
...     new_a += each_a
...     
>>> new_a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

There are many ways to flatten a list. Here are two. I'm sure a Google would come up with many more.

a = [[1,2,3], [4,5,6], [7,8,9]]
b = [num for sublist in a for num in sublist]
print b

import itertools
c = itertools.chain(*a)
print list(c)

thanks that solve my problem

To flatten (unnest) a more complex nested list you need to go to a recursive function ...

def flatten(q):
    """
    a recursive function that flattens a nested list q
    """
    flat_q = []
    for x in q:
        # may have nested tuples or lists
        if type(x) in (list, tuple):
            flat_q.extend(flatten(x))
        else:
            flat_q.append(x)
    return flat_q

# itertools.chain won't work on this nested list
q = [1, [2, 3], [4, 5, 6], [7, [8, 9]]]

print( flatten(q) )  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.