0

e.g., for a sequence of unknown length, what is the most "Pythonic" way of getting the last n elements?

Obviously I could calculate the starting and ending indices. Is there anything slicker?

AdamC
  • 469
  • 1
  • 4
  • 13

3 Answers3

6

Yes, by using negative indices:

last_five = somesequence[-5:]

Negative indices in a slice are relative to the sequence length.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
1

Use negative indexing.

seq[-1] is the last element of a sequence. seq[-3:] gives you the last three.

Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842
1

Try:

sequence[-n:]

(text to make Stack Overflow happy)

Nicholas Riley
  • 42,081
  • 5
  • 99
  • 124