by Sai gowtham

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]

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course