explain enumerate function in python with example
The `enumerate()` function in Python is a built-in function used to add a counter to an iterable, such as a list or a tuple. It returns an enumerate object that contains pairs of an index and the corresponding item from the iterable. This is particularly useful when you need both the index and the value from a sequence in a loop.
### Syntax
```python
enumerate(iterable, start=0)
```
- `iterable`: The collection (like a list or tuple) that you want to enumerate.
- `start`: The starting index value (default is `0`).
### Example
Here's a simple example to illustrate how `enumerate()` works:
```python
# Example list
fruits = ['apple', 'banana', 'cherry', 'date']
# Using enumerate to loop through the list with index
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
```
### Output
```
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Index: 3, Fruit: date
```
### Explanation
In this example:
- We have a list `fruits` containing a few fruit names.
- The `enumerate()` function adds an index to each element of the list.
- The `for` loop iterates through the enumerated object, unpacking the index and the fruit name into two variables: `index` and `fruit`.
- Inside the loop, we print both the index and the corresponding fruit.
### Custom Start Index
You can also specify a different starting index. For example:
```python
# Using enumerate with a custom starting index
for index, fruit in enumerate(fruits, start=1):
print(f"Index: {index}, Fruit: {fruit}")
```
### Output
```
Index: 1, Fruit: apple
Index: 2, Fruit: banana
Index: 3, Fruit: cherry
Index: 4, Fruit: date
```
In this case, the index starts from `1` instead of the default `0`.
The `enumerate()` function is commonly used because it makes the code cleaner and more readable, avoiding the need to manually track the index while iterating over a sequence.