Looping With Python enumerate() (Overview)
In Python, a for
loop is usually written as a loop over an iterable object. This means that you don’t need a counting variable to access items in the iterable. Sometimes, though, you do want to have a variable that changes on each loop iteration. Rather than creating and incrementing a variable yourself, you can use Python’s enumerate()
to get a counter and the value from the iterable at the same time!
In this course, you’ll see how to:
- Use
enumerate()
to get a counter in a loop - Apply
enumerate()
to display item counts - Implement your own equivalent function to
enumerate()
- Unpack values returned by
enumerate()
00:00
Welcome to Python enumerate(): Simplify Looping With Counters. I’m Philipp from Real Python, and today I want to show you how the enumerate()
function helps you to count in for
loops.
00:13 Most calendar-based methods use a four-season model to identify the warmest and the coldest seasons, summer and winter, and in between, spring and fall.
00:23
Why am I talking about seasons? Well, in this course, we’ll work with a list of seasons: Spring
, Summer
, Fall
, and Winter
.
00:30
And your task is to create a Python script to count them. In the end, output should look like this: 1 Spring
, 2 Summer
, 3 Fall
, 4 Winter
.
00:43
First, you will do this without the enumerate()
function. Then you will use it. In lesson number three, you will learn what this enumerate()
function actually is, and then you will use this knowledge to rebuild it. Finally, you will see your very own enumerate()
function in action. All right, let’s get started.
Become a Member to join the conversation.