Python
list manipulation
fetch results
slicing
programming tutorial

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

python
1numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
2
3first_10 = numbers[:10]
4print(first_10)
5# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6
7# Equivalent to numbers[0:10] — start defaults to 0

The slice [:10] means "from the beginning up to (but not including) index 10."

Short Lists — No IndexError

python
1short_list = [1, 2, 3]
2
3first_10 = short_list[:10]
4print(first_10)
5# [1, 2, 3] — returns all 3 elements, no error
6
7# This is safe — slicing never raises IndexError
8print([][:10])  # []

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:

python
1from itertools import islice
2
3# Works with any iterable, not just lists
4def count_up():
5    n = 0
6    while True:
7        yield n
8        n += 1
9
10first_10 = list(islice(count_up(), 10))
11print(first_10)
12# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

islice is memory-efficient — it only pulls 10 elements from the generator without computing the rest.

Using a Loop

python
1numbers = list(range(100))
2
3# Manual approach (less Pythonic but sometimes needed)
4first_10 = []
5for i, item in enumerate(numbers):
6    if i >= 10:
7        break
8    first_10.append(item)
9
10print(first_10)
11# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

With Pandas

python
1import pandas as pd
2
3df = pd.DataFrame({
4    'name': [f'user_{i}' for i in range(50)],
5    'score': range(50)
6})
7
8# First 10 rows
9top_10 = df.head(10)
10print(top_10)
11
12# Or with iloc
13top_10 = df.iloc[:10]
14
15# First 10 of a Series
16scores = df['score'][:10]

With Django QuerySets

python
1# Django ORM — LIMIT 10 at the database level
2recent_posts = Post.objects.order_by('-created_at')[:10]
3
4# This translates to: SELECT ... FROM posts ORDER BY created_at DESC LIMIT 10
5# Efficient: only 10 rows are fetched from the database

With SQLAlchemy

python
1from sqlalchemy import select
2
3# SQLAlchemy 2.0
4stmt = select(User).order_by(User.id).limit(10)
5results = session.execute(stmt).scalars().all()

Deque — First N from a Fixed-Size Collection

python
1from collections import deque
2
3# deque with maxlen automatically keeps only the last N elements
4recent = deque(maxlen=10)
5for i in range(100):
6    recent.append(i)
7
8print(list(recent))
9# [90, 91, 92, 93, 94, 95, 96, 97, 98, 99] — last 10
10
11# For first 10, just use slicing on the original

Performance Comparison

python
1import timeit
2
3data = list(range(1_000_000))
4
5# Slicing — fastest
6timeit.timeit(lambda: data[:10], number=100000)
7# ~0.005s
8
9# islice — slightly slower for lists, but works with generators
10from itertools import islice
11timeit.timeit(lambda: list(islice(data, 10)), number=100000)
12# ~0.02s
13
14# Loop — slowest
15def first_10_loop(lst):
16    result = []
17    for i, x in enumerate(lst):
18        if i >= 10:
19            break
20        result.append(x)
21    return result
22
23timeit.timeit(lambda: first_10_loop(data), number=100000)
24# ~0.08s

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

python
1data = list(range(20))
2
3# First 10
4data[:10]     # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5
6# Last 10
7data[-10:]    # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
8
9# Every other from first 10
10data[:10:2]   # [0, 2, 4, 6, 8]
11
12# First N (variable)
13n = 5
14data[:n]      # [0, 1, 2, 3, 4]

Common Pitfalls

  • Confusing slicing with indexing: my_list[:10] returns a list and never raises IndexError. my_list[10] returns a single element and raises IndexError if 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. Use copy.deepcopy() if you need independent copies.
  • Using islice on lists: For plain lists, slicing ([:10]) is faster than islice. Only use islice for 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. Use queryset[: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

Course illustration
Course illustration

All Rights Reserved.