2

Let's say I have the following list:

the_list = ['one','two','three','four','five']

How can I slice this python list so that my output is the following (print order does not matter):

'one','five','four'

I essentially want to start at index 0 and then slice backwards

Thanks!

2
  • 2
    Slicing of lists has no "wraparound", you can slice forward, backward, and every k-th element, but not a wrap around (both forward and backward), you thus will need to perform two slices and "append" subslices. Commented Oct 19, 2018 at 20:21
  • Ah that is unfortunate, thank you for clarifying however! Commented Oct 19, 2018 at 20:24

2 Answers 2

2

Try this:

the_list[0:1] + the_list[-1:2:-1]

This adds 2 list, where your second list starts from the last element, takes the step size of 2 and in reverse. You can't do multiple slicing but you can select what items to add on or be appended.

Sign up to request clarification or add additional context in comments.

1 Comment

You should also note that this method applies specifically to your sample list. Glad it helped.
0

You could append your first element at the end of the list, and then slice backwards, excluding the first element:

the_list.append(the_list[0]) [the_list[-i] for i in range(1,len(the_list))]

Comments

Your Answer

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.