Enumerate

Sometimes, when we're looping over a container in a for loop, we want access to the index (the current position in the list) of the current item being processed. The for loop doesn't provide us with indexes, but the enumerate function gives us something better: it creates a sequence of tuples, where the first object in each tuple is the index and the second is the original item.

This is useful if we need to use index numbers directly. Consider some simple code that outputs each of the lines in a file with line numbers:

import sys

filename = sys.argv[1]

with open(filename) as file:
for index, line in enumerate(file):
print(f"{index+1}: {line}", end="")

Running this code using its own filename as the input file shows how it works:

1: import sys
2:
3: filename = sys.argv[1]
4:
5: with open(filename) as file:
6: for index, line in enumerate(file):
7: print(f"{index+1}: {line}", end="")

The enumerate function returns a sequence of tuples, our for loop splits each tuple into two values, and the print statement formats them together. It adds one to the index for each line number, since enumerate, like all sequences, is zero-based.

We've only touched on a few of the more important Python built-in functions. As you can see, many of them call into object-oriented concepts, while others subscribe to purely functional or procedural paradigms. There are numerous others in the standard library; some of the more interesting ones include the following: