Fetch first 10 results from a list in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Python's slice syntax my_list[:10] returns the first 10 elements of a list. If the list has fewer than 10 elements, it returns all available elements without raising an error. Slicing creates a new list (shallow copy), leaving the original unchanged. This is the most Pythonic and efficient way to get the first N elements from any sequence.
Basic Slicing
The slice [:10] means "from the beginning up to (but not including) index 10."
Short Lists — No IndexError
Unlike indexing (my_list[10] raises IndexError), slicing gracefully handles lists shorter than the requested size.
Using itertools.islice
For iterators and generators that you do not want to fully materialize:
islice is memory-efficient — it only pulls 10 elements from the generator without computing the rest.
Using a Loop
With Pandas
With Django QuerySets
With SQLAlchemy
Deque — First N from a Fixed-Size Collection
Performance Comparison
Slicing is O(k) where k is the number of elements copied (10 in this case), regardless of the list size. It does not scan the entire list.
Slicing Variations
Common Pitfalls
- Confusing slicing with indexing:
my_list[:10]returns a list and never raisesIndexError.my_list[10]returns a single element and raisesIndexErrorif the list has fewer than 11 elements. - Shallow copy:
my_list[:10]creates a shallow copy. If the list contains mutable objects (dicts, lists), modifying the inner objects affects both the original and the slice. Usecopy.deepcopy()if you need independent copies. - Using
isliceon lists: For plain lists, slicing ([:10]) is faster thanislice. Only useislicefor generators, file handles, or other non-indexable iterables. - Database queries without LIMIT:
list(queryset)[:10]fetches ALL rows from the database, then slices in Python. Usequeryset[:10](Django) or.limit(10)(SQLAlchemy) to push the limit to SQL. - Off-by-one:
[:10]gives indices 0 through 9 (10 elements). If you want elements 1 through 10, use[1:11].
Summary
- Use
my_list[:10]to get the first 10 elements — it is safe, fast, and Pythonic - Slicing never raises
IndexError— returns whatever is available if fewer than 10 - Use
itertools.islice(iterable, 10)for generators and non-indexable iterables - Use
.head(10)in pandas,[:10]on Django QuerySets,.limit(10)in SQLAlchemy - Slicing is O(k) where k is the slice size — it does not scan the entire list

