Python Front and rear range deletion in a list?

PythonServer Side ProgrammingProgramming

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']
raja
Published on 12-Jan-2021 18:13:45
Advertisements