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 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)
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)
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.