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.
word = "cat"
for index, letter in enumerate(word):
print(index, letter)
Output
0 c
1 a
2 t
How This Works
Let’s break it down:
indexstores the positionletterstores 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.
word = "cat"
for index, letter in enumerate(word, start=1):
print(index, letter)
Output
1 c
2 a
3 t
Another Example
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
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
- What does
enumerate()give you? - What number does it start with by default?
- Can you start from
1? - 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.