How do I remove an element from a list by index? I found list.remove(), but this slowly scans the list for an item by value.
To remove an element from a list by its index in Python, you can use the pop()
method. The pop()
method removes and returns the item at the specified index. Here's an example:
python
# Create a list
my_list = [1, 2, 3, 4, 5]
# Remove an element by index
index_to_remove = 2 # Remove the element at index 2 (which is 3)
removed_element = my_list.pop(index_to_remove)
# Print the modified list and the removed element
print("Modified List:", my_list)
print("Removed Element:", removed_element)
In this example, my_list.pop(index_to_remove)
removes the element at index 2 (which is the value 3) and returns it. The modified list will no longer contain the removed element.
Output:
mathematica
Modified List: [1, 2, 4, 5]
Removed Element: 3
Keep in mind that indexing in Python is zero-based, so the first element is at index 0, the second element is at index 1, and so on.
Comments
Post a Comment