-1

I have a list of integers a and b. I want to update the integers in a such that a[i] = a[i] + b[i].

Note: I want to avoid creating a new list. I want to update the existing list.

Currently, I am doing it using a for loop as shown below.

>>> a = [1, 2, 3, 4, 5]
>>> b = [10, 10, 20, 20, 100]
>>> for i in range(len(a)):
...     a[i] += b[i]
...
>>> a
[11, 12, 23, 24, 105]

Can the for loop be replaced with a single-liner code that is equivalent to it?

Lone Learner
  • 18,088
  • 20
  • 102
  • 200
  • I do not understand how this question of mine has been voted to be closed. I do not want to create a new list. Instead, I want to update an existing list. – Lone Learner Feb 16 '14 at 17:00

2 Answers2

3

This could be done pretty simply with a comprehension:

[a_i + b_i for a_i, b_i in zip(a, b)]
wnnmaw
  • 5,444
  • 3
  • 38
  • 63
-1

A very simple way would be to import numpy (if you have it installed, or will be doing similar things).

>>> import numpy as np
>>> a = [1, 2, 3, 4, 5]
>>> b = [10, 10, 20, 20, 100]
>>> a = np.add (a,b)
>>> a
array([ 11,  12,  23,  24, 105])

This and the original question run the risk of the array size differing. This method will always raise a ValueError if that happens. In the first, whether the error exposed depends on which list is shorter.

Fred Mitchell
  • 2,145
  • 2
  • 21
  • 29
  • If you are using `numpy`, wouldn't it be easier to just make `a` and `b` ndarrays, and just do `a+b`? – SethMMorton Feb 11 '14 at 23:11
  • If starting from lists, I think this is easier. An alternative would be to use np.arrays a and b. Then a = a + b would give the desired result. a = np.array ([1, 2, 3, 4, 5])... etc. – Fred Mitchell Feb 11 '14 at 23:23