How to remove an element from a list by index
To remove an element from a list by index in Python, you can use the pop()
method. The pop()
method removes an element at a specific index and returns the element that was removed.
Here's an example:
# Initialize the list
my_list = [1, 2, 3, 4, 5]
# Remove the element at index 2 (which is 3)
removed_element = my_list.pop(2)
# Print the list and the removed element
print(my_list) # [1, 2, 4, 5]
print(removed_element) # 3
Watch a video course
Python - The Practical Guide
You can also use the del
statement to remove an element from a list by index.
Here's an example:
# Initialize the list
my_list = [1, 2, 3, 4, 5]
# Remove the element at index 2 (which is 3)
del my_list[2]
# Print the list
print(my_list) # [1, 2, 4, 5]
Note that the del
statement does not return the removed element, it simply removes it from the list.