I would like to reverse a list, but only where the indices are even.
My goal is that a list like
A = [1, 2, 3, 4, 5]
should become
B = [5, 2, 3, 4, 1]
I know how to print the values where indices are even:
for j in range(len(A)):
if j % 2 == 0:
print(A[j])
But how can I reverse these values to create a new list where the above condition is met for B?
Put differently, I would like indices 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 the values at odd indices should stay the same.
Is there a quick method like this?
A[::-1]
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]