6.1 An Example of enumerate
Going back to the fruits
example I coded out earlier, enumerate
combines both approaches into one. If you read up on the documentation, it mentions that enumerate()
returns an enumerable object: an object that can be counted.
But, to be more specific, enumerate()
returns a tuple of the index of the list’s item and the list item itself - here’s what enumerate()
would yield when I apply it to fruits
:
= ['apple', 'cherry', 'banana', 'mango', 'watermelon', 'tomato']
fruits
for index, fruit in enumerate(fruits):
print(f"Index {index} has {fruit}!")
## Index 0 has apple!
## Index 1 has cherry!
## Index 2 has banana!
## Index 3 has mango!
## Index 4 has watermelon!
## Index 5 has tomato!
The variable index
is used to capture the index of each item in fruits
- the variable fruit
is used to capture each item in fruits
. Of course, you can use any two variable names you want to iterate over an enumerable using enumerate()
, but I would encourage you to make your variable names as intuitive as possible!
6.1.1 Similarities to other programming languages
If you are a gopher like myself (i.e., a Go developer), then you would likely be aware of the range
keyword. I will transcribe the fruits
example shown earlier from Python to Go:
package main
import "fmt"
func main() {
:= [6]string{"apple", "cherry", "banana", "mango", "watermelon", "tomato"}
fruits
for index, fruit := range fruits {
.Printf("Index %d has %s!\n", index, fruits)
fmt}
}
In the above code block, I create a string array with the same fruits in fruits
. I then use the keyword range
that functions similarly to Python’s enumerate()
.