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:
- all and any, which accept an iterable object and return True if all, or any, of the items evaluate to true (such as a non-empty string or list, a non-zero number, an object that is not None, or the literal True).
- eval, exec, and compile, which execute string as code inside the interpreter. Be careful with these ones; they are not safe, so don't execute code an unknown user has supplied to you (in general, assume all unknown users are malicious, foolish, or both).
- hasattr, getattr, setattr, and delattr, which allow attributes on an object to be manipulated by their string names.
- zip, which takes two or more sequences and returns a new sequence of tuples, where each tuple contains a single value from each sequence.
- And many more! See the interpreter help documentation for each of the functions listed in dir(__builtins__).