Let's say I have a list of unknown size, then I can access the last element using:
>>> l = list(range(10))
>>> l[-1]
9
However, is there any way to do this via a slice object like
>>> s = slice(-1, 10)
>>> l[s]
[9]
without knowing the length of my list?
Edit:
I simplified my Question a bit. I am fine with getting a list back, since I am iterating over the sublist later. I just needed a way of getting the last item of list besides being able to get every second element and so on ...
Yes, just use None
as the end
argument:
In [53]: l[slice(-1, None)]
Out[53]: [9]
This will of course produce a list [9]
, rather than the 9
in your question, because slicing a list always produces a sublist rather than a bare element.
If your objective is to pass arguments which you can use to index a list, you can use operator.itemgetter
:
from operator import itemgetter
L = range(10)
itemgetter(-1)(L) # 9
In my opinion, for this specific task, itemgetter
is cleaner than extracting a list via a slice, then extracting the only element of the list.
Note also that this works on a wider range of objects than just lists, e.g. with range
as above.
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