-4

i want to make a loop, that every time it runs, the corresponding item in a list is changed.

for example:

list=[10, 20, 30]  

the first run will add 1 to 10
the second rung will subtract 5 from 20
the third run will add 2 to 30
and the loop starts over again.

how can i do this? thanks for answering!

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Kevin Liu
  • 73
  • 5
  • 1
    Can you give a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) about what you want to do? or the code that you have tried so far? – Mazdak May 20 '15 at 12:31
  • i don't know the syntax of modifying certain item in the list based on the times if runs of the loop – Kevin Liu May 20 '15 at 12:36
  • possible duplicate of [Python - get position in list](http://stackoverflow.com/questions/364621/python-get-position-in-list) – SiHa May 20 '15 at 12:59

3 Answers3

3

You may use the built-in zip function like this:

changes = [1, -5, 2]
data = [10, 20, 30]

result = [(a + b) for a, b in zip(data, changes)]

and then

>>> result
[11, 15, 32]

If you want to do that in a loop, go ahead:

while <your condition>:
    data = [(a + b) for a, b in zip(data, changes)]
bagrat
  • 7,158
  • 6
  • 29
  • 47
1

As a simple example you can create a rules dict add add each value per index.

rules = {1: 1, 2: -5, 3: 2}
my_list = [10, 20, 30]

print [v + rules[i+1] for i, v in enumerate(my_list[:])]

We will iterate at each index and add the corresponded rule from rules if the key won't exists at the rules dict you will get a raise of KeyError

You ca further read more on lists here and on python list comprehension here

Kobi K
  • 7,743
  • 6
  • 42
  • 86
1

Try the following code:

for i in range(len(l)):
if i == 0:
    l[0] += 1
elif i == 1:
    l[1] -= 5
elif i == 2:
    l[2] += 2

print l
kenorb
  • 155,785
  • 88
  • 678
  • 743
rajeshv90
  • 574
  • 1
  • 7
  • 17