# Define a list of integers my_list = [1, 2, 3, 4, 5] # Remove the element at index 2 (which is the third element) del my_list[2]
# The list now contains [1, 2, 4, 5]
To remove an element from a list by its index, you can use the del statement in Python.
Keep in mind that this operation modifies the list in place and does not return a new list. If you want to create a new list with the element removed, you can use the pop() method or slice the list to create a new list.
Here's an example using pop():
# Define a list of integers my_list = [1, 2, 3, 4, 5] # Remove the element at index 2 (which is the third element) and store it in a variable removed_element = my_list.pop(2) # The list now contains [1, 2, 4, 5] and removed_element is 3And here's an example using slicing:
# Define a list of integers my_list = [1, 2, 3, 4, 5] # Create a new list with the element at index 2 (which is the third element) removed new_list = my_list[:2] + my_list[3:] # The list my_list is unchanged and new_list contains [1, 2, 4, 5]
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.