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



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

example 1

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

returns

0 1 b

example 2

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

returns

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

but how enumerate know when unpack values returns?

enumerate() knows nil unpacking. for statement this.

the target part of for statement acts regular assignment does, can name multiple targets , right-hand-side value expected sequence same number of elements. enumerate() always produces tuple of 2 elements; first for loop has 2 targets unpack to, sec has 1 target.

the principle same if assigned tuple 2 names:

i, v = (0, 'a')

vs.

x = (0, 'a')

see for statement documentation:

each item in turn assigned target list using standard rules assignments

as assignment statements documentation, explains rules of assignment target lists:

assignment of object target list recursively defined follows.

if target list single target: object assigned target. if target list comma-separated list of targets: object must iterable same number of items there targets in target list, , items assigned, left right, corresponding targets.

when utilize just for x in have single target , (0, 'a') tuple assigned it. when utilize for i, v in have comma-separated list of targets, tuple iterable same number of items targets, , 0 bound i , 'a' bound v.

python iterator

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -