Open In App

How to Get First N Items from a List in Python

Last Updated : 21 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Accessing elements in a list has many types and variations. For example, consider a list "l = [1,2,3,4,5,6,7]" and N=3, for the given N, our required result is = [1,2,3].

This article discusses several ways to fetch the first N elements of a given list.

Method 1: Using List Slicing

This problem can be performed in 1 line rather than using a loop using the list-slicing functionality provided by Python. 

Python
l = [1, 2, 3, 4, 5, 6, 6]

N = 2

res = l[:N]

print(str(res))

Output
[1, 2]

Explanation: l[:N] gives the first 'N' elements of the list.

Method 2: Using Loops

1. Using While Loop

In this approach, we will be using a while loop with a counter variable starting from 0 and as soon as its value becomes equal to the number of elements we would like to have we will break the loop.

Python
l = [1, 2, 3, 4, 5, 6, 6, 6, 6]

N = 4
i = 0
while True:
    print(test_list[i])
    i = i + 1
    if i == N:
        break

Output
1
2
3
4

2. Using for Loop

This approach is more or less similar to the last one because the working of the code is approximately similar only benefit here is that we are not supposed to maintain a counter variable to check whether the required number of first elements has been printed or not.

Python
l = [1, 2, 3, 4, 5, 6, 6, 6, 6]

N = 3

for i in range(N):
    print(l[i])

Output
1
2
3

Method 3: Using List comprehension

Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list. It is faster, requires fewer lines of code, and transforms an iterative statement into a formula.

Python
l = [1, 2, 3, 4, 5, 6, 6, 6, 6]

N = 5

res = [idx for idx in l if idx < N + 1]

print(str(res))

Output
[1, 2, 3, 4, 5]

Method 4: Using Slice Function

Python slice() function is used to get the first N terms in a list. This function returns a slice object which is used to specify how to slice a sequence. One argument is passed in this function which is basically the last index till which we want to print the list.

Python
l = [1, 2, 3, 4, 5, 6, 6, 6, 6]

N = 3

print(l[slice(N)])

Output
[1, 2, 3]

Method 5: Using the itertools module

The itertools module in Python provides several functions that allow us to work with iterators more efficiently. One such function is islice, which returns an iterator that produces selected items from the input iterator, or an iterable object, by skipping items and limiting the number of items produced.

Python
from itertools import islice

l = [1, 2, 3, 4, 5, 6, 6]
N = 3

res = islice(l, N)
print(list(res))

Output
[1, 2, 3]

Next Article
Practice Tags :

Similar Reads