greole
greole

Reputation: 4771

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

Upvotes: 5

Views: 3297

Answers (3)

Coding Wala
Coding Wala

Reputation: 41

If you were to access the last element of the list:

n = int(input())
user_input = [int(input) for i in range(n)]
last_element = user_input[-1]

Here we have used negative indices concept in lists.

Upvotes: 0

jpp
jpp

Reputation: 164843

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.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

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.

Upvotes: 8

Related Questions