+2 votes
in Programming Languages by (7k points)

I want to append all elements of a list to a big list, but I am not getting the desired output. The append() function appends the whole list as an element. Here is the example.

>>> a=[1,2,3,4,5,6]
>>> b=[7,8,9]
>>> a.append(b)
>>> a
[1, 2, 3, 4, 5, 6, [7, 8, 9]]

I want a = [1, 2, 3, 4, 5, 6, 7, 8, 9] instead of [1, 2, 3, 4, 5, 6, [7, 8, 9]]. How can I fix it?

1 Answer

0 votes
by (13.5k points)

There are two ways that I know. You can either use '+' operator or extend() function to append all elements of a list to another list. Have a look at the following example.

>>> a=[1,2,3,4,5,6]
>>> b=[7,8,9]
>>> a=a+b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]


>>> a=[1,2,3,4,5,6]
>>> b=[7,8,9]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]

...