8
\$\begingroup\$

I am relatively new to python and I am still trying to learn the basics of the language. I stumbled upon a question which asks you to rearrange the list by modifying the original. What you are supposed to do is move all the even index values to the front (in reverse order) followed by the odd index values.

Initial:

 0 1 2 3 4 5 6
[3, 5, 2, 8, 7, 9, 0]

Rearranged:

 6 4 2 0, 1, 3, 5
[0, 7, 2, 3, 5, 8, 9]

This is how I approached the question:

even = []
odd = []
for i in range(len(l)):
 if i % 2 == 0:
 even.append(i)
 else:
 odd.append(i)
even = even[::-1]
index = even + odd
l2 = []
for i in index:
 l2.append(l[i])
for i in range(len(l)):
 l[i] = l2[i]

Although it works, and does what is being asked, I was wondering if there is a more efficient way to get the result. I feel that creating three empty lists just to rearrange one list is not the best approach.

Any input would be greatly appreciated.

Vogel612
25.5k7 gold badges59 silver badges141 bronze badges
asked May 8, 2018 at 1:30
\$\endgroup\$
0

1 Answer 1

8
\$\begingroup\$

I'm not sure if you are actually trying to solve this problem in-place, but based on what you have done, you could condense your code by using Python list slices instead of separating even and odd indices in a for loop. Slices work by

list[start_index:end_index:step]

So, you could get the even indices with

l[::2][::-1]

which gets the even indices in reverse order, and the odd indices by offsetting the start by 1,

l[1::2]

This works because a step size of 2 means you get every other #, so starting at 0 results in all even indices and starting at 1 results in all odd indices. Without the start index it starts at 0, and without the end index it goes until the end of the list.

This combines into a single line, assigning using slice notation to keep the modification in-place,

l[:] = l[::2][::-1] + l[1::2]
answered May 8, 2018 at 6:11
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.