Enumerate() in a for Loop
The enumerate()
function proves valuable when we need to access both the value and its index within any sequence, such as a list or string.
For instance, a list serves as an ordered data structure that associates each item with a unique index number. Utilizing this index number, we can conveniently access or alter the corresponding value.
The syntax for using enumerate()
is: for index, value in enumerate(___)
Note
As a quick reminder: index refers to the position of an element. In Python, we begin counting indexes from 0.
Examine the following code:
How does the code work?
![](https://codefinity-content-media.s3.eu-west-1.amazonaws.com/a8aeafab-f546-47e9-adb6-1d97b2927804/1_8_%D0%BE%D1%8B%D0%B2%D0%BB%D0%B0%D0%B2%D1%8B%D0%BB.gif)
Task
Count the quantity of numbers in the list that are multiples of three.
- Configure the
for
loop withenumerate()
to operate onnumbers
, employingi
for indexes andv
for values. - Establish the condition that checks whether a number is a multiple of three.
- Increment the
counter
by1
if the number meets the condition. - Display the value of the
counter
.
Everything was clear?
Course Content
Python Loops Tutorial
Python Loops Tutorial
Enumerate() in a for Loop
The enumerate()
function proves valuable when we need to access both the value and its index within any sequence, such as a list or string.
For instance, a list serves as an ordered data structure that associates each item with a unique index number. Utilizing this index number, we can conveniently access or alter the corresponding value.
The syntax for using enumerate()
is: for index, value in enumerate(___)
Note
As a quick reminder: index refers to the position of an element. In Python, we begin counting indexes from 0.
Examine the following code:
How does the code work?
![](https://codefinity-content-media.s3.eu-west-1.amazonaws.com/a8aeafab-f546-47e9-adb6-1d97b2927804/1_8_%D0%BE%D1%8B%D0%B2%D0%BB%D0%B0%D0%B2%D1%8B%D0%BB.gif)
Task
Count the quantity of numbers in the list that are multiples of three.
- Configure the
for
loop withenumerate()
to operate onnumbers
, employingi
for indexes andv
for values. - Establish the condition that checks whether a number is a multiple of three.
- Increment the
counter
by1
if the number meets the condition. - Display the value of the
counter
.
Everything was clear?