Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading