TIL: enumerate() Has a start Parameter You Probably Never Used
When working with lists in Python, enumerate() is a handy function that allows us to loop over both the index and value of each item. By default, enumerate() starts counting from 0, which is usually what we want. However, there are cases where we might want to start counting from a different number, like 1.
Let's take a look at an example:
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(f"Fruit {i}: {fruit}")
# Output:
# Fruit 0: apple
# Fruit 1: banana
# Fruit 2: cherry
for i, fruit in enumerate(fruits, start=1):
print(f"Fruit {i}: {fruit}")
# Output:
# Fruit 1: apple
# Fruit 2: banana
# Fruit 3: cherry
As you can see, by passing start=1 to enumerate(), we can start counting from 1 instead of the default 0. This can be useful when working with data that's 1-indexed, like human-readable lists or CSV files.
Takeaway: The start parameter of enumerate() is a hidden gem that can simplify your code when working with 1-indexed data, so keep it in mind for your next Python project!
Follow me on Dev.to for daily Python tips and quick guides!
🛠️ Recommended Tool
If you found this useful, check out Content Creator Ultimate Bundle (Save 33%) — $29.99 and designed for developers like you.
Get instant access to our best-selling AI Dev Boost, HTML Landing Page Templates, AI Prompts for Developers, and Python Automation Scripts Pack, perfect for content creators and marketers looking to elevate their game. This bundle is a must-have for anyone looking to create stunning content, build high-converting landing pages, and drive real results. With these tools, you'll be able to create engaging content, build beautiful landing pages, and boost your online presence.
Top comments (0)