Flat_Eric Contemplating Data Type Conversions

Enumerate

enumerate()

enumerate() is a built in Python function that adds a counter to any iterable automatically. Instead of manually creating and incrementing a counter variable yourself, enumerate() handles it for you and returns both the index and the item on each iteration.

It is not as commonly used as range() but when you need to know the position of each item as you loop through a collection, enumerate() is the cleanest and most Pythonic way to do it.

The structure looks like this:

for i, item in enumerate(iterable):

Just like iterating over a dictionary with .items(), we unpack two values on each iteration. i holds the current index and item holds the current value. The index starts at 0 by default but you can change the starting value by passing a second argument to enumerate().

enumerate() with a String

Each character in the string is returned along with its position. Try changing the string and observe how the index updates automatically.

enumerate() with a List

This is the most common use of enumerate(). Instead of using range(len(list)) to track the index, you can wrap the list directly.

enumerate() with a Tuple

Works exactly the same as a list. Each item is returned with its index.

enumerate() with a Dictionary

When used with a dictionary, enumerate() returns the index and the key by default. If you need the values as well you can combine it with .items().

Changing the Start Index

By default enumerate() starts counting from 0. You can change this by passing a start value as the second argument. This is useful when you want to display a numbered list to a user starting from 1 instead of 0.

Loading quiz...

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Basic enumerate()

Exercise 2: Find the Index

Exercise 3: enumerate() with a String

Exercise 4: enumerate() with a Condition

Exercise 5: enumerate() with a Dictionary

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course