Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I slice a list till end with negative indexes

I learned that Python lists can also be traversed using negative index, so I tried to slice/sublist a list using negative index, but I cannot slice it till end.

My list is:

areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]

Knowing that slicing syntax is [start:end] and end index is not calculated, I did upstairs = areas[-4:0] but this doesn't give me last element of the list.

like image 712
pjj Avatar asked Nov 16 '25 12:11

pjj


1 Answers

areas[-4:0] translates to areas[len(areas) - 4: 0], which is effectively slicing from a higher index to a lower. Semantically, this doesn't make much sense, and the result is an empty list.

You're instead looking for:

>>> areas[-4:]
['bedroom', 10.75, 'bathroom', 9.5]

When the last index is not specified, it is assumed you slice till the very end.


As an aside, specifying 0 would make sense when you slice in reverse. For example,

>>> areas[-4:0:-1]
['bedroom', 20.0, 'living room', 18.0, 'kitchen', 11.25]

Happens to be perfectly valid. Here, you slice from len(areas) - 4 down to (but not including) index 0, in reverse.

like image 163
cs95 Avatar answered Nov 18 '25 07:11

cs95