python list delete
时间: 2023-06-02 14:02:37 浏览: 136
To delete an element from a Python list, you can use the `del` statement or the `remove` method.
1. Using `del` statement:
The `del` statement can be used to remove an element from a list by specifying its index.
Syntax:
```python
del list_name[index]
```
Example:
```python
fruits = ['apple', 'banana', 'cherry']
del fruits[1] # remove 'banana'
print(fruits) # Output: ['apple', 'cherry']
```
2. Using `remove` method:
The `remove` method can be used to remove an element from a list by specifying its value.
Syntax:
```python
list_name.remove(value)
```
Example:
```python
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'cherry']
```
Note: If the value is not found in the list, the `remove` method will raise a `ValueError` exception.
阅读全文