Deleting from Lists
Deleting a single element
To remove a single element from a list, we can use the del
statement along with the index of the element we want to delete. For example, let’s consider a list of space movies. Suppose we want to delete the movie at index 2
.
space_movies = ['Interstellar', 'Gravity', 'The Martian', 'Apollo 13', 'Star Wars']print(space_movies)del space_movies[2]print(space_movies)
The above code snippet will delete ‘The Martian’
from the list and print the list of space movies before and after deletion.
Deleting multiple elements
In order to delete multiple elements, we can use slicing along with the del
statement. We can simply specify the range of indices to delete, and the elements within that range will be removed.
Let’s suppose we want to delete the movies at indices 1 and 2.
space_movies = ['Interstellar', 'Gravity', 'The Martian', 'Apollo 13', 'Star Wars']del space_movies[1:3]print(space_movies)
In the code above, elements at indices 1 and 2 (‘Gravity’
and ‘The Martian’
) will be deleted by passing the range 1:3
(1 is inclusive, 3 is exclusive) and the updated list will be printed.
Removing by value
Alternatively, if we know the value we want to remove but not the corresponding index, we can make use of the remove()
method.
space_movies = ['Interstellar', 'Gravity', 'The Martian', 'Apollo 13', 'Star Wars']print(space_movies)space_movies.remove('Gravity')print(space_movies)
This code removes the movie ‘Gravity’
from the list and prints the updated space movies list.
Clearing the entire list
To delete all elements from a list, we can use the clear()
method.
space_movies = ['Interstellar', 'Gravity', 'The Martian', 'Apollo 13', 'Star Wars']space_movies.clear()print(space_movies)
After executing this code snippet, the space_movies
list becomes empty.
The pop()
method
The pop()
method can be used to remove and return an element at a specific index. If no index is provided, it removes and returns the last element by default.
space_movies = ['Interstellar', 'Gravity', 'The Martian', 'Apollo 13', 'Star Wars']removed_movie = space_movies.pop(2)print("The removed movie is = " + removed_movie)print(space_movies)
This code removes the movie at index 2 (e.g., ‘The Martian’
) and first prints the removed movie, followed by the updated list.
Note: Remember to use these methods carefully, as they modify the original list.