1

I was doing some practice with lists, arrays and matrices in python and I got confused at something.

if I do:

list1 = [1,2,3,4]
list2 = [2,3,4,5]

print list1 + list2

Output:

I get [1,2,3,4,2,3,4,5]

I think it was like yesterday I was doing something similar but I got

Output2:

[3,5,7,9] 

the actual addition of the values of each respective element on both lists. But I was actually expecting it to be the first output, but it added the values.

I haven't done linear algebra or prob&stats in a while. What was the method called for the output I got in output1? and output2? I've confused myself bad.

edit: http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.add.html If you look at the 2nd example they do a 3x3 array + 1x3 array. I thought if there not the same dimension you can't add them?

Nabz
  • 126
  • 2
  • 13
  • 1
    Lists and arrays have entirely different behavior. Always be careful which one you're using. `np.matrix` is awful; don't use it. – user2357112 Jan 10 '16 at 06:23
  • Lists are lists, vectors are vectors. The `+` operator concatenates two lists. If you want vectorised addition, either use `numpy` arrays or subclass `list` and overload arithmetic methods. – Eli Korvigo Jan 10 '16 at 06:25

3 Answers3

2

When using standard lists, addition is defined as concatenation of the two lists

import numpy as np

list1 = [1,2,3,4]
list2 = [2,3,4,5]

print list1 + list2
# [1, 2, 3, 4, 2, 3, 4, 5]

When using numpy types, addition is defined as element-wise addition rather than list concatenation.

array1 = np.array(list1)
array2 = np.array(list2)

print array1 + array2
# [3 5 7 9]

This is often called a vectorized operation. In cases where arrays are large it can be faster than iterating over the structures, since the vectorized operation utilize a highly optimized implementation which is provided by numpy.

David Maust
  • 8,080
  • 3
  • 32
  • 36
0

If you do not understand zip or numpy - Assuming both lists list1 and list2 have same length, this will do your work

[a[i]+b[i] for i in xrange(len(a))]

PS: simply using list1 + list2 would only concatenate these two lists. To add each of the element you need to iterate through the lists.

Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
0

You can get "Output2" canonically with sum() and zip():

result = [sum(item) for item in zip(list1, list2)]

If you put each list1, list2, etc. into a container (such as a tuple or another list, e.g. lists = [list1, list2]) you can instead use zip(*lists) and then not have to change that code for any quantity of lists.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97