2

suppose i have a list like this:

my_list = [0,1,2,3,4,5] # range(5)

i want to print this:

[2,1,0]

my python script is:

print(my_list[2:-1:-1])

but it prints an empty list!

is this a bug in python(2 and 3!)?

i wont use any trick like:

num_of_elems_i_want = 3
print(my_list[::-1][len(my_list) - num_of_elems_i_want:])

or third party modules..

2 Answers 2

5

You could slice the list as shown:

print(my_list[2::-1])      # L[start:end:step]

EDIT :

The result that you had obtained is not a Bug.

Remember that traversal of the list elements takes place from left to right and there are no elements till end=-4[viz elements: 5 → 0 → 1 → 2] from start=2. So, an empty list is returned as a result.

For the same reason, you could also do print(my_list[2:-7:-1])

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

2 Comments

Doesn't answer the question (whether the result of the original is a bug).
@StefanPochmann Novice programmers with questions often assume that there is a bug in the language when they are certain their code is right. In reality, it is never a bug in the language
1

You can also invert your list permanently for other uses:

my_list.reverse()
print(my_list[-4:-1])

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.