Get First n Elements of List in Python Tutorial Example

26-Apr-2023

.

Admin

Get First n Elements of List in Python Tutorial Example

Hi Dev,

This post will give you an example of getting the first n elements of the List in Python tutorial example. We will use Python to get the first n elements of the list. you can understand the concept of how to get the first n elements of a list in Python. This article will give you a simple example of a Python list getting the first n elements.

We can use [0:N] to get the first n elements of the Python list. In this example, we will take the myList variable with a number of lists. Then we will add an n variable to get the first n number of items in the Python list. let's see the examples:

Example:


main.py

# Create New List with Item

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

n = 4

# Python Get Get 2 Elements from List

newList = myList[0:n]

print(newList)

Output:

[1, 2, 3, 4]

#Python