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

Reverse list where indexes are even

I would like to reverse a list but only where the indexes are even.
So my goal is that a list that starts like :

A = [1,2,3,4,5]

Should look like :

B = [5,2,3,4,1]

So to check where indexes are even I write :

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

for j in range(0,len(A)):
     if j % 2 == 0:
         print(A[j])        #prints all the values at equal indexes. 

How would I only reverse A where the above condition is met to for B?
So to explain more , I would like indexes of array A to swap where they are even . Indexes that are even are : 0 , 2 , 4 where the values of A are
1 , 3 , 5 . I want these values to switch to 5,3,1 but indexes that are not even should stay the same.

Is there a quick method like :

A[::-1]

>Solution :

Others like Michael Szczesny have suggested more concise solutions like:

A[::2] = reversed(A[::2])

already in the comments, but here is one that is more verbose in case it helps you see what is going on.

We’ll assume that the list starting out is already sorted.

A = [1,2,3,4,5]


#We isolate the even indices
even_indices = []
for i in range(len(A)):
    if i%2==0:
        even_indices.append(A[i])

#We reverse the even indices
even_indices = list(reversed(even_indices))
print(even_indices)

B = []
#We put everything back together, if the index is odd, we use the value from A, if not, we use the value from even_indices, which has been reversed.
for i in range(len(A)):
    if i%2==1:
        B.append(A[i])
    else:
        B.append(even_indices[i//2])


print(B)

Output:

[5, 3, 1]
[5, 2, 3, 4, 1]
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