Alireza Afzal ghaei Alireza Afzal ghaei - 2 months ago 6x
Python Question

python print 3 first elements of list in reverse mode

suppose i have a list like this:

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

i want to print this:


my python script is:


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..


You could slice the list as shown:

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


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]. So, an empty list is obtained as a result.

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