Multiplying by 2 every other element in a list starting from the end of the list

I want to make a list that multiplies its elements by 2 starting from the end with a step of -2. For example:

a = [1, 2, 3, 4, 5, 6, 7] 
# I want it to return a = [2, 2, 6, 4, 10, 6, 14]

I had some ideas but nothing I try works. Take a look at my code:

a = [1, 2, 3, 4, 5, 6, 7]
a = [i*2 for i in a[-1::-2]]
print(a)

#or
a = [1, 2, 3, 4, 5, 6, 7]
for i in a[-1::-2]:
    i *= 2
#returns only 14, 10, 6, 2

>Solution :

You had almost the correct logic. Loop on the indices an assign back to the list:

a = [1, 2, 3, 4, 5, 6, 7] 

for i in range(len(a)-1, -1, -2):
    a[i] *= 2

Output:

[2, 2, 6, 4, 10, 6, 14]

Leave a Reply