How to remove an element from a Python list?

To remove an element from a Python list, you can use the following method:

  1. delete
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)  # Output: [1, 2, 4, 5]
  1. delete
my_list = [1, 2, 3, 4, 5]
del my_list[2]
print(my_list)  # Output: [1, 2, 4, 5]
  1. remove the last added element
my_list = [1, 2, 3, 4, 5]
removed_element = my_list.pop(2)
print(my_list)  # Output: [1, 2, 4, 5]
print(removed_element)  # Output: 3
Leave a Reply 0

Your email address will not be published. Required fields are marked *