Guide to Remove an Element From a List in Python

my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]

# removing a specific element.
my_list.remove("to")
print(my_list)
['hello', 'world', 'welcome', 'techgeekbuzz']
#removing an element that is not present in the list.
my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]
my_list.remove("too")
print(my_list)
Traceback (most recent call last):
File "listexample.py", line 3, in <module>
my_list.remove("to0")
ValueError: list.remove(x): x not in list

2. The clear() Method

my_list = [1,2,3,4,5,6,7]
# remove all elemets from the list
my_list.clear()
print(my_list)
[]

3. The pop() Method

my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]

# removing the last element from the list.
popped = my_list.pop()
print("The poped element is:", popped)
print("Now the list is:",my_list)
The popped element is: techgeekbuzz
Now the list is: ['hello', 'world', 'welcome', 'to']
my_list = ["hello", "world", "welcome", "to", "techgeekbuzz"]
# removing a specific element using the index value.
popped = my_list.pop(2)
print("The poped element is:", popped)
print("Now the list is:",my_list)
The popped element is: welcome
Now the list is: ['hello', 'world', 'to', 'techgeekbuzz']

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store