← Back to Blog

Position and value — at the same time

The problem...

You're looping through a string. You have the character. But you also need to know where you are.

So you create a counter. You increment it manually. It works — but it's extra code for something Python can handle for you.

word = "Bull"
index = 0

for letter in word:
    print(f"Index {index}: {letter}")
    index += 1

You just learned how to do this. Now forget it — there's a cleaner way.

The idea!

enumerate() gives you both the position and the value on every iteration. No counter. No manual increment. Just unpack and use.

The syntax

for index, item in enumerate(sequence):
    # index — current position
    # item — current value

Your first enumerate

word = "Bull"

for index, letter in enumerate(word):
    print(f"Index {index}: {letter}")
# Index 0: B
# Index 1: u
# Index 2: l
# Index 3: l

Same result as before. No counter. No increment. Python handles it.

Starting from a different index

By default, enumerate() starts at 0. You can change that.

word = "Bull"

for index, letter in enumerate(word, start=1):
    print(f"Position {index}: {letter}")
# Position 1: B
# Position 2: u
# Position 3: l
# Position 4: l

Useful when you want to show positions in a human-friendly way — starting from 1, not 0.

A real example

word = input("Enter a word: ")

for index, letter in enumerate(word, start=1):
    print(f"Letter {index} is '{letter}'")
# Enter a word: Horn
# Letter 1 is 'H'
# Letter 2 is 'o'
# Letter 3 is 'r'
# Letter 4 is 'n'

Heads up!

  • enumerate() returns two values — unpack both: index, item
  • Default start is 0 — use start=1 for human-friendly output
  • The variable names are up to you — i, letter or pos, char — both valid
  • No need for a manual counter — enumerate() replaces it

The mindset shift

Stop thinking: "I'll track the position myself."

Start thinking: "If I need position and value — enumerate() has both."

What you should understand now

  • enumerate() gives you position and value on every iteration
  • Default start is 0 — change it with start=
  • Unpack both values: for index, item in enumerate(sequence)
  • No manual counter needed — cleaner, less code, same result
[ login to bookmark ] // copied! 33 views · 1 min
// resources
Code Example enumerate_function.py
← prev Keeping score — the loop counter next → What if your loop had two lanes?
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.