If you want to use the pop()
method to remove multiple elements from a list in Python, you can’t directly remove multiple elements at once. However, you can use a loop or list comprehension to achieve the desired result.
Note: The pop()
method is used to remove and return a single element from a list based on its index.
Pop multiple elements Python example
Simple example code.
Using a loop with pop()
:
my_list = [1, 2, 3, 4, 5, 6]
indices_to_remove = [1, 3]
# Sort the indices in descending order to avoid index errors
indices_to_remove.sort(reverse=True)
for index in indices_to_remove:
my_list.pop(index)
print(my_list)
Using list comprehension:
my_list = [1, 2, 3, 4, 5, 6]
indices_to_remove = [1, 3]
my_list = [my_list[i] for i in range(len(my_list)) if i not in indices_to_remove]
print(my_list)
Output:
When using pop()
, it’s essential to handle the indices carefully to avoid index errors. Sorting the indices in descending order ensures that you remove elements from the end of the list first, which won’t affect the subsequent indices to remove. Alternatively, list comprehension provides a more concise and efficient way to achieve the same result without modifying the original list.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.