Try using negative indices for the range - a_list[-2:-5]

I need explanation for this code
a_list = [23, ‘hello’, None, 3.14, fruits, 3 <= 5]
a_list[-2:-5]
not clear to me that return an empty list

negative index simply represents index value counting from the end.
for instance ,
list = [1,2,3,4,5,6]

list[-1] == list[5]

and,
for list [-3 : -1 ] the starting index is interpreted as => len(list) - 3 = 6 - 3 = 3
and the ending index as => len(list) - 4 -1 = 6 - 1- 1 = 4

In your case,
the starting index is (6 - 2) = 4 and ending index is (6 - 5 -1 ) = 0
As you can seen starting index > ending index, it cannot be sliced. In order to slice the list you can either use list[-5:-2] or you can do reverse slicing by using additional parameter in the array i.e list[-2 : -5 : -1].

ps. list [starting index : ending index ] , here the sliced list will include starting indexed element to ending index ( excluding ending index).

2 Likes