Excerpt

## A brief explanation about the built-in enumerate function in Python
Play this article
### Table of contents
- Introduction
- Enumerate Function
- Changing the start index
- Conclusion
```plain text
# Loop over a list and print the index and value of each element'apple', 'banana', 'mango']
index, fruit in enumerate(fruits):
print(index, fruit)
```
The output of this code will be:
```plain text
0 apple
1 banana
2 mango
```
As you can see, the enumerate function returns a tuple containing the index and value of each element in the sequence. You can use the for loop to unpack these tuples and assign them to variables, as shown in the example above.
## Changing the start index
By default, the enumerate function starts the index at 0, but you can specify a different starting index by passing it as an argument to the enumerate function:
```plain text
# Loop over a list and print the index (starting at 1) and value of each element
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
```
The output will be:
```plain text
1 apple
2 banana
3 mango
```
The enumerate function is often used when you need to loop over a sequence and perform some action with both the index and value of each element. For example, you might use it to loop over a list of strings and print the index and value of each string in a formatted way:
```plain text
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(f'{index+1}: {fruit}')
```
And, the output is,
```plain text
1: apple
2: banana
3: mango
```
In addition to lists, you can use the enumerate function with any other sequence type in Python, such as tuples and strings. Here's an example with a tuple:
```plain text
# Loop over a tuple and print the index and value of each element
colors = ('red', 'green', 'blue')
for index, color in enumerate(colors):
print(index, color)
```
And here's an example with a string:
```plain text
# Loop over a string and print the index and value of each character
s = 'hello'
for index, c in enumerate(s):
print(index, c)
```
Well, that's a wrap for now!! Hope you folks have enriched yourself today with lots of known or unknown concepts. I wish you a great day ahead and till then keep learning and keep exploring!!
Read articles from Swapnoneel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Hello, I'm Swapnoneel Saha and I am currently in my freshman year. I am a Front-End Developer, Programmer and an open-source enthusiast. I am passionate about exploring new technologies and contributing to open-source projects. In my free time, I enjoy learning about new programming languages and staying up-to-date with the latest developments in the tech industry. Follow my blog to stay informed about my latest articles and projects.