67

Suppose I have a list with X elements

[4,76,2,8,6,4,3,7,2,1...]

I'd like the first 5 elements. Unless it has less than 5 elements.

[4,76,2,8,6]

How to do that?

Minilouze
  • 25
  • 10
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

4 Answers4

119

You just subindex it with [:5] indicating that you want (up to) the first 5 elements.

>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]

Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!

>>> x[5:]
[11, 12]
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 14
    This is commonly known as slicing. –  Oct 08 '09 at 00:29
  • 16
    This creates a *new* list, it doesn't trim the existing one. To trim in-place, use `del` on a slice; e.g. `del listobj[-x:]` will remove the last *x* elements from the list object. – Martijn Pieters Aug 18 '16 at 14:09
46

To trim a list in place without creating copies of it, use del:

>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>> 
warvariuc
  • 57,116
  • 41
  • 173
  • 227
1
l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1
>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
sepp2k
  • 363,768
  • 54
  • 674
  • 675