
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- How to remove an element from a list by index in Python?
- How to remove an element from a Java List?
- How to remove an element from Array List in C#?
- How to remove an object from a list in Python?
- Java Program to remove an element from List with ListIterator
- How to remove index list from another list in python?
- Python – Remove Tuples from a List having every element as None
- How to remove an element from an array in Java
- Python Program to remove a specific digit from every element of the list
- How to remove an element from ArrayList in Java?
- How to remove the last element from a set in Python?
- How to delete/remove an element from a C# array?
- Remove Tuples from the List having every element as None in Python
- How to remove an element from DOM using jQuery?
- How to remove a class name from an element with JavaScript?
