Use slice syntax to get the first n elements of a list in Python. Just use the slicing syntax [ ]
by passing a 0:n
as an argument to it.
new_list = source_list[:N]
Where 0 is the start index (it is included) and n is the end index (it is excluded).
Python first n elements of the list
A simple example code gets the first 3 elements from the given list:
numList = [4, 5, 2, 6, 7, 8, 10]
firstThree = numList[0:3]
print("First 3: ", firstThree)
Output:
List with First N Elements using For Loop
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(new_list)
List with First N Elements using List Comprehension
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(new_list)
Make sure that n
is within the bounds of the list to avoid an IndexError
. If the list has fewer than n
elements, the slice will include all available elements without raising an error.
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.