4

I am new to python and I was just trying some list manipulations. I have three lists

A = [10,20,30,40,50,60]
B = [22,44,66,88,12,10]
C = [2,4,6,8,10,20]

I want to iterate over these three lists and for each value of C I want to add half of that value to the corresponding values of A and B. For example for the 1st iteration - half = 2/2= 1 So A = 10 + 1 and B = 22+1 So the final lists should look something like this

A = [11,22,33,44,55,70]
B = [23,46,69,92,17,20]
C = [2,4,6,8,10,20]
newbie
  • 325
  • 2
  • 4
  • 19

3 Answers3

6

As long as the lists all have the same lengths, you can iterate with enumerate() function:

for i, n in enumerate(C):
    A[i] += n/2
    B[i] += n/2

>>> A
[11, 22, 33, 44, 55, 70]
>>> B
[23, 46, 69, 92, 17, 20]
Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
  • Nice, but remember if you're on Python 2 you might get surprising results with `n / 2`. Do `n / 2.` or put `from __future__ import division` at the top of the script. If on Python 3, disregard this comment. – mwaskom Mar 21 '14 at 05:07
  • @mwaskom Good point, that will depend on what does the OP wants. If he wants to keep the division integer then n/2 will do ok, if not, in Python2 he can always do `n/2.` to get `float` result. Thanks for mentioning. – Paulo Bu Mar 21 '14 at 10:10
1
>>> A, B = zip(*((a + c/2, b + c/2) for a, b, c in zip(A, B, C)))
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
  • Beat me to it. Dang you. :D – Travis Griggs Mar 21 '14 at 00:27
  • 1
    +1 I like oneliners but remember, _Simple is better than complex_. :) – Paulo Bu Mar 21 '14 at 00:29
  • A one-line solution like this isn't really useful for learning or for practical use; according to http://stackoverflow.com/a/725818/1577850 using `+` for two lists will tell Python to make a new copy of `A` and `B` which is not what OP is looking for. – SimonT Mar 21 '14 at 00:30
0

ITs best to use Numpy arrays.

import numpy as np
A, B, C = map(np.array, [A, B, C])
A, B = A - C/2, B - C/2
ssm
  • 5,277
  • 1
  • 24
  • 42