title | description | tags | headerImage | datePublished | lastModified |
---|---|---|---|---|---|
Python - First n items from dictionary / List |
Extract first n items from any iterable. |
python |
/post/python.png |
2020-02-28 |
2020-02-28 |
Fetch first* n items from a collection using the following techniques:
islice
method from itertools
can be used to extract the given number of items from any iterable.
from itertools import islice
list(islice(iterable, n))
*Order is defined by iterable.
record = {'name': 'mighty', 'handler': '@DM8tyProgrammer', ...}
list(islice(record, 3))
students = [("Alex", 30), ("Bob", 50"), ...]
list(islice(sorted(students, key = lambda s: s[1]), 5))
If the type of collections is known to be list
, then square bracket can also be convenient.
numbers = [1, 2, 4, 5]
print(numbers[:2])