Python | Front and rear range deletion in a list

Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element deletion. It is a good utility whose solution can be useful to have. Let’s discuss certain ways in which this can be performed.

Method #1 : Using list slicing + del operator
The del operator can be clubbed with the slicing action to delete the front and rear elements from a list to obtain a cropped version of list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# front and rear deletion 
# using del operator + list slicing
  
# initializing list 
test_list = [2, 3, 5, 7, 9, 10, 8, 6]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# using del operator + list slicing
# front and rear deletion 
del test_list[-2:], test_list[:2]
  
# printing result 
print ("The cropped list is : " +  str(test_list))

chevron_right


Output :



The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The cropped list is : [5, 7, 9, 10]

 

Method #2 : Using list slicing
Above method can be modified and the use of del operator can be omitted to achieve this particular task. We can slice a list in a way that specific number of elements are removed from the list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# front and rear deletion 
# using list slicing
  
# initializing list 
test_list = [2, 3, 5, 7, 9, 10, 8, 6]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# using list slicing
# front and rear deletion 
res = test_list[2 : -2]
  
# printing result 
print ("The cropped list is : " +  str(res))

chevron_right


Output :

The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The cropped list is : [5, 7, 9, 10]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.