Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply odd indices by 2?

Tags:

python

list

So I'm writing a function that is going to multiply each number at an odd index in a list by 2. I'm stuck though, as I really don't know how to approach it.

This is my code.

def produkt(pnr):
    for i in pnr:
        if i % 2 != 0:
            i = i * 2
    return pnr

If I, for example, type produkt([1,2,3]) I get [1,2,3] back but I would want it to be [2,2,6].

like image 748
Lss Avatar asked Dec 08 '25 08:12

Lss


2 Answers

note that modifying i in your example does not change the value from the input list (integers are immutable). And you're also mixing up the values with their position.

Also, since indices start at 0 in python, you got it the wrong way.

In those cases, a simple list comprehension with a ternary expression will do, using enumerate to be able to get hold of the indices (making it start at 1 to match your case, you can adjust at will):

[p*2 if i%2 else p for i,p in enumerate(pnr,1)]

(note if i%2 is shorter that if i%2 != 0)

like image 65
Jean-François Fabre Avatar answered Dec 09 '25 22:12

Jean-François Fabre


using list comprehensions:

multiply odd numbers by 2:

[x*2 if x%2 else x for x in pnr]

After clarification of question wording: multiply numbers at odd indices by 2:

[x*2 if i%2 else x for i,x in enumerate(pnr)]
like image 40
Zinki Avatar answered Dec 09 '25 22:12

Zinki