How Does Python Enumerate Function - Python Quick Tips Work?

Python’s enumerate function is like having a special friend who counts things for you as you go through them one by one.

Imagine you have a bag of your favorite candies, let's say 5 candies: chocolate, gummy, mint, sour, and licorice. You want to know not just the names of the candies but also their positions in the bag. That’s where enumerate comes in handy! It gives each candy a number as you take them out.

How Enumerate Works

Think of enumerate like your teacher reading out roll call. As she says each name, she also says the student's position: "1. Alice", "2. Bob", and so on. In Python, it works the same way, it gives both the item and its number as you go through a list.

For example:

candies = ["chocolate", "gummy", "mint", "sour", "licorice"]
for count, candy in enumerate(candies):
 print(f"{count + 1}. {candy}")

This will print:

  • 1. chocolate
  • 2. gummy
  • 3. mint
  • 4. sour
  • 5. licorice

So enumerate is just a friendly helper who counts things for you, no magic, just simple counting!

Take the quiz →

Examples

  1. Using enumerate to track both the position and value of items in a list, like counting apples in a basket.
  2. Adding numbers while tracking which number you're on using enumerate.
  3. enumerate helps count how many times you've repeated an action by keeping track of each step.

Ask a question

See also

Discussion

Recent activity