How to Remove Last Two or More Elements from List in Python?

31-Mar-2023

.

Admin

How to Remove Last Two or More Elements from List in Python?

Hi Dev,

This post will give you an example of how to remove the last two or more elements from the list in python. We will look at an example of removing the last two or more elements from the list python. if you want to see an example of how to remove the last two or more elements from the list in python then you are in the right place. this example will help you python remove elements from the end of the list.

I will give you examples of how to remove the last two, three, four, five, and ten elements from the list. you can view one by one example that way you can use it what you need. we will use len() function to delete the last elements. let's see the examples:

Example 1: Python Remove Last 2 Elements from List


main.py

# Create New List with Item

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

n = 2

# Python Remove Last 2 Elements from List

newList = myList[:len(myList) - n]

print(newList)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 2: Python Remove Last 5 Elements from List

main.py

# Create New List with Item

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

n = 5

# Python Remove Last 5 Elements from List

newList = myList[:len(myList) - n]

print(newList)

Output:

[1, 2, 3, 4, 5, 6, 7]

#Python