- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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']
Advertisements