Python: Fetch first 10 results from a list
PythonPython Problem Overview
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)
?
Python Solutions
Solution 1 - Python
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 these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation - thanks Daren)
Solution 2 - Python
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]
Solution 3 - Python
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
Solution 4 - Python
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]