- Using
remove()
: Removes the first occurrence of the value.pythonmy_list = [1, 2, 3, 4]
my_list.remove(3)
print(my_list) # [1, 2, 4]
- Using
pop()
: Removes an item by index.pythonmy_list = [1, 2, 3, 4]
my_list.pop(2)
print(my_list) # [1, 2, 4]
- Using
del
: Deletes an item by index or slices.pythonmy_list = [1, 2, 3, 4]
del my_list[1]
print(my_list) # [1, 3, 4]
- Using List Comprehension: To remove multiple occurrences.
python
my_list = [1, 2, 3, 4, 2]
my_list = [x for x in my_list if x != 2]
print(my_list) # [1, 3, 4]
How to Remove Item from a List in Python
RELATED ARTICLES
0 Comments
Oldest