7

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?

1
  • 3
    array.append(other_array) will never lead to the cited error message. Please show your real code. Commented Nov 21, 2011 at 15:54

4 Answers 4

30

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]
Sign up to request clarification or add additional context in comments.

1 Comment

The question was about array, not list.
22

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

Comments

2

Array (as in numpy.array or array module) or list? Because given your error message, it seems the later.

Anyway, you can use the += operator, that should be overridden for most container types, but the operands must be of the same (compound) type.

1 Comment

The += will add the values, it does not affect the structure.
0

Usually, if you want to expand a structure to the right (axis=1) or at the bottom (axis=0), you should have a look at the numpy.concatenate() function, see Concatenate a NumPy array to another NumPy array.

np.concatenate(arr1, arr2, axis=0) 

is probably what is needed here, adding a new row in a nested array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.