A programmer commonly requires both the current position index and corresponding element value when iterating over a sequence.
Example below demonstrates how using a for loop with range() and len() to iterate over a sequence generates a position index but requires extra code to retrieve a value:
Similarly, a for loop that iterates over a container obtains the value directly, but must look up the index with a function call:
The enumerate() function retrieves both the index and corresponding element value at the same time, providing a cleaner and more readable solution.
The enumerate() function yields a new tuple each iteration of the loop, with the tuple containing the current index and corresponding element value.
In the example above, the for loop unpacks the tuple yielded by each iteration of enumerate(origins) into two new variables: "index" and "value".
Unpacking is a process that performs multiple assignments at once, binding comma-separated names on the left to the elements of a sequence on the right.
Ex: num1, num2 = [350, 400] is equivalent to the statements num1 = 350 and num2 = 400.