DEV Community

Adrian Perea
Adrian Perea

Posted on • Originally published at adrianperea.dev

8

Better Python for Loops Using enumerate

It's a common use case to iterate over a list together with its index. Traditionally, this has been done by using a for loop, utilizing range and len to create a list of indices. The items of the list then are accessed using [] notation, like so:

shopping_cart = ['apple', 'cereal', 'banana', 'cola']

for i in range(len(shopping_cart)):
    print(f'{i}: {shopping_cart[i]}')

# 0 apple
# 1 cereal
# 2 banana
# 3 cola
Enter fullscreen mode Exit fullscreen mode

But this solution is very imperative, reminiscent of older programming languages. We have a better, more pythonic solution.

Using the enumerate keyword, we can get an iterator that already gives both the item and index of the list. Using this, we can simplify the above code as follows:

shopping_cart = ['apple', 'cereal', 'banana', 'cola']

for i, item in enumerate(shopping_cart):
    print(f'{i}: {item}')

# 0 apple
# 1 cereal
# 2 banana
# 3 cola
Enter fullscreen mode Exit fullscreen mode

I personally think that this solution is cleaner, more elegant, and simpler to write.


Hey! My name is Adrian. I'm a software engineer who likes to write. If you liked this, why not follow me on Twitter?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay