229

Is there a way we can fetch first 10 results from a list. Something like this maybe?

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

list.fetch(10)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Amyth
  • 32,527
  • 26
  • 93
  • 135

4 Answers4

453
list[:10]

will give you the first 10 elements of this list using slicing.

However, note, it's best not to use list as a variable identifier as it's already used by Python: list()

To find out more about this type of operation, you might find this tutorial on lists helpful and this link: Understanding slicing

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Levon
  • 138,105
  • 33
  • 200
  • 191
  • Note that this creates a copy of the first 10 elements. Depending on your needs you might prefer lazy, non-copying slicing with itertools.islice. – georg Jun 05 '12 at 12:34
  • 2
    @thg435 -- This doesn't create a copy of the elements in the list, only a new reference to them. It does however, create a new list ... – mgilson Jun 05 '12 at 12:49
  • @mgilson: it depends on what you understand under "element". Python containers always hold pointers to objects, and this creates 10 new pointers (+ one new list object). – georg Jun 05 '12 at 12:52
  • 3
    @thg435 -- python has no pointers. (if you want pointers, you use C ;) python has references. the point here is that you don't create new objects, only new references to them...We're saying the same thing, but the way your original statement was written was misleading (at least to me) so I thought I would clarify. – mgilson Jun 05 '12 at 12:58
  • 2
    @mgilson: agreed, I should have better written "creates a copy of that part of the list". – georg Jun 05 '12 at 13:01
36

check this

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    
list[0:10]

Outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
user1409289
  • 492
  • 5
  • 13
  • explicit vs implicit: use explicit, this slicing conforms to python zen code! :) more clear. – Rakibul Haq Apr 25 '19 at 05:22
  • To be clear, the `0` is not required here, it's implied. The way I think of it is this is saying "from 0 to 10" while `list[:10]` would mean "up to 10", which is simpler. – wjandrea Feb 13 '23 at 19:34
20

The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice function:

from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
    print item
Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73
13

Use the slicing operator:

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[:10]
ddk
  • 1,813
  • 1
  • 15
  • 18