Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending two arrays together in Python

I've been working in Python with an array which contains a one-dimensional list of values. I have until now been using the array.append(value) function to add values to the array one at a time.

Now, I would like to add all the values from another array to the main array instead. In other words I don't want to add single values one at a time. The secondary array collects ten values, and when these are collected, they are all transfered to the main array. The problem is, I can't simply use the code 'array.append(other_array)', as I get the following error:

unsupported operand type(s) for +: 'int' and 'list'

Where am I going wrong?

like image 215
CaptainProg Avatar asked Nov 21 '11 15:11

CaptainProg


2 Answers

Lists can be added together:

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

and one can be easily added to the end of another:

>>> a += b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
like image 67
cel106 Avatar answered Oct 05 '22 11:10

cel106


You are looking for array.extend() method. append() only appends a single element to the array.

like image 45
pajton Avatar answered Oct 05 '22 12:10

pajton