pythonloops

Python loop over nested generator with two variables, in one for loop


Hell all. This is when using Python 3.
Say I have a tuple/list/generator, which elements are always are a two elements tuple.
A simple sample would be this: ( ( 1,2) (3,4) )
I want to loop (no nested loops), with two loop variables, akin to what is done when using enumerate.
I.e., the code:

for fst,scnd in : Some_operator( ( ( 1,2) (3,4) ) ):
    print( fst*scnd )

Should output:

2
12

The question is: Does Some_operator exists, and if so, what is it?
Thanks.


Solution

  • Well, just delete Some_operator and you'll get what you want as this is how the default unpacking works in this context.

    for fst, scnd in ((1, 2), (3, 4)):
        print(fst * scnd)
    

    outputs

    2
    12