The Python Oracle

Python: Fetch first 10 results from a list

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Question
00:23 Accepted answer (Score 442)
00:51 Answer 2 (Score 34)
01:06 Answer 3 (Score 20)
01:31 Answer 4 (Score 13)
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/1089...

Accepted answer links:
[list()]: https://docs.python.org/library/function...
[tutorial on lists]: https://docs.python.org/tutorial/introdu...
[Understanding slicing]: https://stackoverflow.com/questions/5092...

Answer 3 links:
[itertools]: http://docs.python.org/library/itertools...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 465


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




ANSWER 2

Score 40


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]



ANSWER 3

Score 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



ANSWER 4

Score 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]