What are the different methods of list in python? Explain with example
Python provides a variety of methods to manipulate lists. Below are several commonly used list methods, along with explanations and examples for each.
### 1. `append()`
Adds an item to the end of the list.
```python
fruits = ['apple', 'banana']
fruits.append('orange')
print(fruits) # Output: ['apple', 'banana', 'orange']
```
### 2. `extend()`
Extends the list by appending elements from another iterable (like another list).
```python
fruits = ['apple', 'banana']
fruits.extend(['orange', 'mango'])
print(fruits) # Output: ['apple', 'banana', 'orange', 'mango']
```
### 3. `insert()`
Inserts an item at a specified position.
```python
fruits = ['apple', 'banana']
fruits.insert(1, 'orange') # Insert at index 1
print(fruits) # Output: ['apple', 'orange', 'banana']
```
### 4. `remove()`
Removes the first occurrence of a specified value.
```python
fruits = ['apple', 'banana', 'orange']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'orange']
```
### 5. `pop()`
Removes and returns an item at the specified position (default is the last item). If the list is empty, it raises an `IndexError`.
```python
fruits = ['apple', 'banana', 'orange']
last_fruit = fruits.pop()
print(last_fruit) # Output: 'orange'
print(fruits) # Output: ['apple', 'banana']
```
### 6. `clear()`
Removes all items from the list.
```python
fruits = ['apple', 'banana', 'orange']
fruits.clear()
print(fruits) # Output: []
```
### 7. `index()`
Returns the index of the first occurrence of a specified value. Raises a `ValueError` if the value is not found.
```python
fruits = ['apple', 'banana', 'orange']
index_of_banana = fruits.index('banana')
print(index_of_banana) # Output: 1
```
### 8. `count()`
Returns the number of times a specified value appears in the list.
```python
fruits = ['apple', 'banana', 'orange', 'banana']
count_banana = fruits.count('banana')
print(count_banana) # Output: 2
```
### 9. `sort()`
Sorts the items of the list in place. The default is ascending order. You can provide an optional `reverse` argument to sort in descending order.
```python
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 9]
```
### 10. `reverse()`
Reverses the order of the items in the list.
```python
fruits = ['apple', 'banana', 'orange']
fruits.reverse()
print(fruits) # Output: ['orange', 'banana', 'apple']
```
### 11. `copy()`
Returns a shallow copy of the list.
```python
fruits = ['apple', 'banana', 'orange']
fruits_copy = fruits.copy()
print(fruits_copy) # Output: ['apple', 'banana', 'orange']
```
### Summary
These methods allow you to effectively manage and manipulate lists in Python. Each of these methods is versatile and can be combined with others to produce complex behaviors. Understanding these methods is critical for mastering list operations in Python programming.