The precedence of unpack operators

I had a hard time understanding the n-length groups idiom. I was confused
by the unpack operator and the multiplication operator for repeatition.
I was not clear which comes first until today.

zip(* [iter(s)]*n )
zip(*([iter(s)]*n)) # with parentheses
zip(*(n*[iter(s)])) # put repeatition count first

Is it necessary to add two unpack operators * positional
and ** dictionary unpack in the operator precedence section.
Where should they be if it is necessary?


Edit:
I understand it more now.

s = [1, 2, 3, 4, 5, 6, 7, 8]
print(list (zip(       s     ))) # zip() calls next() in each iteration
print(list (zip(  iter(s)    )))
print(list (zip(*[iter(s) ]  )))
print(list (zip(*[iter(s) ]*1))) # [ ] square brackets for multiplication
print(list (zip(*[iter(s) ]*2)))
print(list (zip(*[iter(s) ]*3)))
print(tuple(zip(*(iter(s),)*2))) # use all parentheses

Thanks

https://docs.python.org/3/library/functions.html#zip
https://docs.python.org/3/reference/expressions.html#operator-precedence

All of these are the same. The multiplication will happen first - it’s not possible to “multiply” the result of an unpack, because the unpacking doesn’t produce a value, it’s a special syntax used for the function call. (The unpacking “operator” doesn’t appear in the precedence table you found in the documentation because it is not actually an operator - it is not part of an expression.) The last two examples are just swapping the list and the number around; that clearly doesn’t matter - multiplying a list works in either order.

However, you may find it clearer to use the parentheses - and easier to read.

2 Likes