Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "enumerate" know when to unpack the values returned?

Example 1

for i, v in enumerate({'a', 'b'}):
    print(i, v)

returns

0 a
1 b

Example 2

for x in enumerate({'a', 'b'}):
    print(x)

Returns

(0, 'a')
(1, 'b')

But how does enumerate know when to unpack the values it returns?

like image 976
Anton Tarasenko Avatar asked Jan 18 '26 14:01

Anton Tarasenko


1 Answers

enumerate() knows nothing about unpacking. It is the for statement that does this.

The target part of the for statement acts like a regular assignment does, you can name multiple targets and the right-hand-side value is expected to be a sequence with the same number of elements. enumerate() always produces a tuple of two elements; your first for loop has two targets to unpack it to, the second only has one target.

The principle is the same as if you assigned a tuple to two names:

i, v = (0, 'a')

vs.

x = (0, 'a')

See the for statement documentation:

Each item in turn is assigned to the target list using the standard rules for assignments

as well as the assignment statements documentation, which explains the rules of assignment to target lists:

Assignment of an object to a target list is recursively defined as follows.

  • If the target list is a single target: The object is assigned to that target.
  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

When you use just for x in you have a single target and the (0, 'a') tuple is assigned to it. When you use for i, v in you have a comma-separated list of targets, the tuple is an iterable with the same number of items as targets, and thus 0 is bound to i and 'a' is bound to v.

like image 73
Martijn Pieters Avatar answered Jan 21 '26 08:01

Martijn Pieters