0

Here I'm trying to merge this two lists, making one whit all items.

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

def flatten(n):
    s=[]
    for x in n:
        s.append(x)
    return s

print flatten(n)

I'm trying to have as a result

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

but I'm getting

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

I dont understand why, I think I'm clearly assigning each value to the list 's' in the for loop.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
piguiligui
  • 39
  • 1
  • 3

3 Answers3

3

You're appending to the list. Each sublist is appended to the new list as its own item, exactly the way it was originally. You want to extend the list instead:

s.extend(x)
kindall
  • 178,883
  • 35
  • 278
  • 309
2

Use extend, instead of append

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

def flatten(n):
    s=[]
    for x in n:
        s.extend(x)
    return s

print flatten(n)

Best of luck.

Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
2

You should be using list.extend, append is appending each sublist not adding just the contents. x is each sublist so just appending the sublist is obviously going to give you a list of lists again.

You can also use itertools.chain to flatten the list:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

print(list(chain.from_iterable(n)))

Or use a list comp:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

print([ele for sub in n for ele in sub])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321