- 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
How to remove an element from a list in Python?
A list in Python is a linear data structure where elements are stored in contiguous memory locations and elements are accessed by their indexes.
We may sometimes need to remove an element from a list in Python. There are various inbuilt functions to achieve this.
pop()
This deletes or removes the element at the index passed as an argument in pop().
Example
lst=[1,2,3,4,5] lst.pop(2) print(lst)
Output
[1, 2, 4, 5]
The above code snippet shows that the pop(2) removes the element at index 2.
remove()
This function removes the first occurrence of the element passed as argument in remove().
Example
lst=[1,2,3,2,4,5] lst.remove(2) print(lst)
Output
[1, 3, 2, 4, 5]
The above code snippet shows that the remove(2) removes the first occurrence of element 2 ,i.e. at index 1.
del[a:b]
This function is used to remove elements from index a(inclusive) to index b(not inclusive) in a list.
Example
lst=[0,1,2,3,4,5,6,7,8,9] del lst[2:5] print(lst)
Output
[0, 1, 5, 6, 7, 8, 9]
The above code removes the elements from index 2 to 5 (i.e. elements 2,3,4) from the list.
clear()
This function is used to remove all the elements from the list.
Example
lst=[0,1,2,3,4,5,6,7,8,9] lst.clear() print(lst)
Output
[]
All the elements are removed from the list, but an empty list is left.