Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract the last two items from the list, strings or tuples in Python?

Tags:

python

slice

User will input the string, list or tuples.

I have to extract the first do and the last two values. For the first two values:

ls[:2]

For the last two values how can I do it?

If n is the total number of values the last two item can be sliced as:

[n-1:]

How can I put down in the code?

like image 957
Joyfulgrind Avatar asked Nov 30 '22 23:11

Joyfulgrind


2 Answers

ls[-2:]

Negative numbers in slices are simply evaluated by adding len(ls), so this is the same as ls[len(ls) - 2:]. For more information on slices, refer to the Python tutorial or this excellent stackoverflow answer.

like image 95
phihag Avatar answered Dec 05 '22 02:12

phihag


ls[-2:]

would be the way to do it, as negative indexes count from the end.

like image 34
glglgl Avatar answered Dec 05 '22 00:12

glglgl