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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With