In this post, you will learn the various ways to find the first n elements of the list in python.
Problem Statement:
You have to Find the First N elements of a list in Python.
Examples to get the first N elements of List in Python
Create a sample list that will be used to implement the following examples. You can create a list in python using the square bracket.
sample_list = [ 10,20,30,40,50,60,70,80]
Example 1: Get the first N elements using slicing.
You can Get the first n elements from the list using slicing. Just use the “: N ” inside the square bracket.
Syntax :
sliced_list = your_list[: N]
If you want to get the first six elements from the list. Then the value of N is 6.
Full Code
sample_list = [ 10,20,30,40,50,60,70,80]
sliced_list = sample_list [: 5]
print(sliced_list)
Output

In the same way, you can get the first 4 elements. Here the value of N will be 4.
Full Code
sample_list = [ 10,20,30,40,50,60,70,80]
sliced_list = your_list[: 3]
print(sliced_list)
Output
[10,20,30,40]
Example 2: Using For Loop
You can get the first n elements using the for loop also. Here you have to first create an empty list and while looping through all the elements just append the element to the empty list.
sample_list = [ 10,20,30,40,50,60,70,80]
N= 5
sliced_list =[]
for i in sample_list:
if len(sliced_list) < N:
sliced_list.append(i)
print(sliced_list)
Inside the loop length of the empty list has been checked. If it is less than the N then add the element to it otherwise don’t insert it.
Output

Example 3: Using List Comprehension
You can also get the first N elements using the list comprehension. List comprehension is the single-line statement that acts like a loop.
Run the below lines of code to get the elements.
sample_list = [ 10,20,30,40,50,60,70,80]
N= 5
sliced_list = [x for x in sample_list[:N]]
print(sliced_list)
Output

Conclusion
In this post, you have known the various ways to find the first n elements of the list in python. You can use slicing to get the first n elements from the list or use the for loop to iterate through the list and get the first n elements. At last, you can also use the list comprehension to conditional loop in a single line of the statement.
Leave a Reply