CodingNic

Loops and Iteration

Enumerate

Loops and Iteration 18 min read

Enumerate

Enumerate

Sometimes you need two things in a loop:

  • The item
  • The position of the item

For example:

  • Show each letter with its number
  • Show each name with its position
  • Show menu items with numbers

Python gives us a helpful tool called enumerate().

What Is Enumerate?

enumerate() gives each item a number while looping.

It is often used when you need both the position and the value.

python
word = "cat"

for index, letter in enumerate(word):
    print(index, letter)

Output

text
0 c
1 a
2 t

How This Works

Let’s break it down:

  • index stores the position
  • letter stores the item
  • Python gives both values during each loop

The first position starts at 0.

Starting From 1

You can choose a different starting number.

python
word = "cat"

for index, letter in enumerate(word, start=1):
    print(index, letter)

Output

text
1 c
2 a
3 t

Another Example

python
names = ["Ali", "Sara", "John"]

for number, name in enumerate(names, start=1):
    print(number, name)

Why Enumerate Is Useful

Without enumerate(), getting positions can be harder.

It makes your code cleaner and easier to read.

Code Along

python
colors = ["Red", "Blue", "Green"]

for number, color in enumerate(colors, start=1):
    print(number, color)

Mini Challenge

Build a numbered menu.

Steps:

  • Create a list with these items:
    Home, Profile, Settings
  • Use enumerate()
  • Print each item with a number starting from 1

Real World Use Case

Apps use enumerate() for menus, ranked lists, numbered results, and showing item positions.

Quiz

  1. What does enumerate() give you?
  2. What number does it start with by default?
  3. Can you start from 1?
  4. Why is enumerate() useful?

Assignment

Create a program that shows each letter in your name with its position number.

Summary

You learned how enumerate() gives items and their positions during a loop, making loops more useful and organized.