Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting last element of a list of unknown size using slices

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

like image 897
greole Avatar asked Jun 26 '18 08:06

greole


2 Answers

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.

like image 130
Mazdak Avatar answered Sep 23 '22 05:09

Mazdak


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.

like image 35
jpp Avatar answered Sep 25 '22 05:09

jpp