How to get first n elements of a list in Python
In this tutorial, we are going to learn about how to get the first n elements of a list in Python.
Consider, we have the following list:
numList = [12, 13, 14, 15, 16]
To access the first n elements from a list, we can use the slicing syntax [ ]
by passing a 0:n
as an arguments to it .
0 is the start index (it is inculded).
n is end index (it is excluded).
Here is an example, that gets the first 3 elements from the following list:
numList = [12, 13, 14, 15, 16]
firstThree = numList[0:3]
print(firstThree) # [12, 13, 14]