Get first N elements of the List


Get Python List with First N Elements

There are many ways to get given Python List with first N elements.

Python - Get List with First N Elements

You can use slicing to slice the given list and get a new list with the first N elements of the original or source list.

Or, you can access the list using index, and use a looping statement like for loop to get the first N elements.

Another way would be to use list comprehension. This is an overkill to get the first N elements, but would be educative to learn Python programming.

So, based on the requirement, you may choose one of the above approaches to get or create a new list with the first N elements from the source list.

1. List with First N Elements using Slicing

The syntax to get the list with first N elements using slicing is

new_list = source_list[:N]

The source list is not modified. A new list is created with the first N elements of source list.

Following is an example program, where we initialize a list, and copy the first N elements of the list to a new list using slicing.

Python Program

source_list = [8, 4, 7, 3, 6, 1, 9]
N = 4
new_list = source_list[:N]
print(source_list)
print(new_list)

Output

[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3]

The new list contains first 4 elements of source list.

2. List with First N Elements using For Loop

To get the first N elements of a list, use for loop with range(0, N), create a new empty list, and append the elements of source list to new list in the for loop.

range(0, N) iterates from 0 to N-1, insteps of 1. N is not included.

list.append(element) appends given element to the list.

Following is an example program, where we initialize a list, and use for loop to get the first N elements of the given list.

Python Program

source_list = [8, 4, 7, 3, 6, 1, 9]
N = 4
new_list = []
for index in range(0, N):
    new_list.append(source_list[index])
print(source_list)
print(new_list)

Output

[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3]

3. List with First N Elements using List Comprehension

In the following program, we use list comprehension with if condition and collect those items of source list whose index is less than N.

Python Program

source_list = [8, 4, 7, 3, 6, 1, 9]
N = 4
new_list = [x for index, x in enumerate(source_list) if index < N]
print(source_list)
print(new_list)

Output

[8, 4, 7, 3, 6, 1, 9]
[8, 4, 7, 3]

Summary

In this tutorial of Python Examples, we learned how to get the list without its last element, with the help of slicing and pop() method.