Python Front and rear range deletion in a list?


Using list slicing

In this approach we use slicing from both the front and rear of the list. The result is stored into a new list. The number of elements to be sliced can be a variable.

Example

 Live Demo

listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Given list
print("Given list : " ,listA)

# No of elements to be deleted
# from front and rear
v = 2

new_list = listA[v:-v]

print("New list : ",new_list)

Output

Running the above code gives us the following result −

Given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
New list : ['Tue', 'Wed', 'Thu']

Using del

In this approach we use the del keyword. We first apply del with slicing from the rear and then apply it from the front.

Example

 Live Demo

listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Given list
print("Given list : " ,listA)

# No of elements to be deleted
# from front and rear
v = 2
# Using del and Slicing
del listA[-v:], listA[:v]
print("New list : ",listA)

Output

Running the above code gives us the following result −

Given list : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
New list : ['Tue', 'Wed', 'Thu']

Updated on: 12-Jan-2021

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements