Jacob Wheeler
Jacob Wheeler

Reputation: 53

How do I perform math on every other number in a list?

E.g.: How do I change

a = [1,2,3,4]

to this:

a = [2,2,6,4]

so every other element is doubled?

Upvotes: 0

Views: 245

Answers (4)

Onitz
Onitz

Reputation: 46

Though I do like the neat tricks used in the other answers, perhaps a more verbose and less-language specific explanation of what's going on is as follows:

for i in range(0, len(a)):   # Iterate through the list
    if i%2 == 0:             # If the remainder of i ÷ 2 is equal to 0...
        a[i] = a[i] * 2      # Change the current element to twice what it was

Upvotes: 1

Pax Vobiscum
Pax Vobiscum

Reputation: 2639

There is another way to take two steps at a time a little more intuitive, like this

for i in range(len(yourList)/2):
    yourList[2*i] = 2*yourList[2*i]

Upvotes: 1

Amber
Amber

Reputation: 526633

You can loop through every other index:

for index in range(0, len(your_list), 2):
    your_list[index] *= 2

You can also do it using slice assignment, as @mgilson notes:

your_list[::2] = [x*2 for x in your_list[::2]]

While this is certainly more concise, it may also be more confusing for the average person reading through the code - assigning to a slice with a non-default skip factor isn't very intuitive.

Upvotes: 2

mgilson
mgilson

Reputation: 309929

If you want to do it in place, you can use slice assignment:

>>> a[::2] = [x*2 for x in a[::2]]
>>> a
[2, 2, 6, 4]

Upvotes: 4

Related Questions