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
  • 457
  • 1
  • 4
  • 14

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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Use negative indexing.

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

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

Try:

sequence[-n:]

(text to make Stack Overflow happy)

Nicholas Riley
  • 43,532
  • 6
  • 101
  • 124