8

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?

razlebe
  • 7,134
  • 6
  • 42
  • 57
Joyfulgrind
  • 2,762
  • 8
  • 34
  • 41

3 Answers3

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

Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
6
ls[-2:]

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

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

if you have a list like this: a_list = [1,2,3] you can get last two [2,3] elements by a_list[-2:]

juankysmith
  • 11,839
  • 5
  • 37
  • 62