tags:

views:

245

answers:

3

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?

A: 
l = [4,76,2,8,6,4,3,7,2,1]
l = l[:5]
nasufara
Just don't call your lists `list` in real code!
too much php
@too Of course, this is only made for demonstration purposes :D
nasufara
+14  A: 

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
This is commonly known as slicing.
Steve314
+1  A: 
>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
sepp2k