how to delete two values from a list in Python
To delete two values from a list in Python, you can use either the `remove()` method or by using indices. Here's how you can do both:
### Using the `remove()` Method
The `remove()` method removes the first occurrence of a specified value from the list. If you want to remove two values, you can call `remove()` twice:
```python
my_list = [10, 20, 30, 40, 50, 60, 30]
# Removing two values by using the remove() method
my_list.remove(30) # Removes the first occurrence of 30
my_list.remove(40) # Removes the first occurrence of 40
print(my_list) # Output: [10, 20, 50, 60, 30]
```
### Using the Index Method
To remove items using their indices, you can use the `del` statement. You need to know the indices of the items you want to remove.
```python
my_list = [10, 20, 30, 40, 50, 60]
# Removing two values by using their indices
del my_list[2] # Removes the item at index 2 (30)
del my_list[3] # Removes the item that is now at index 3 (50)
print(my_list) # Output: [10, 20, 40, 60]
```
**Note:** If you remove items by index, ensure you adjust for the fact that the list shrinks after each removal. This is why if you remove from the last index first, you don’t have to adjust the index.
If you want to remove the items in a single line without adjusting indices, you can do so like this:
```python
my_list = [10, 20, 30, 40, 50, 60]
# Removing two values by using their indices (larger index first)
del my_list[4] # Removes the item at index 4 (50)
del my_list[2] # Removes the item at index 2 (30)
print(my_list) # Output: [10, 20, 40, 60]
```
This approach ensures that removing one item doesn't affect the index of the other item you want to remove.
Comments
Post a Comment