Reputation: 3441
I am trying to make sense of starred expressions in python. When I use it in python functions, it allows to call functions with different number of arguments:
def my_sum(*args):
results = 0
for x in args:
results += x
return results
print(my_sum(1,2,3))
>>6
print(my_sum(1,2,3,4,5,6,7))]
>>28
However when I use it in an assignment, it works like this:
a, b, *c, d = [1,2,3,4,5,6,7,8,9,10]
print(a,b,c,d)
>>1 2 [3, 4, 5, 6, 7, 8, 9] 10
*a, b, *c, d = [1,2,3,4,5,6,7,8,9,10]
print(a,b,c,d)
*a, b, *c, d = [1,2,3,4,5,6,7,8,9,10]
^
SyntaxError: multiple starred expressions in assignment
Can someone explain to me what is happening behind this assignment that doesn't allow multiple starred expressions?
Upvotes: 1
Views: 347
Reputation: 296049
The language doesn't allow this because it would be ambiguous, and allowing ambiguities is contrary to the Zen of Python:
In the face of ambiguity, refuse the temptation to guess.
Let's say you run:
*a, b, *c, d = [1,2,3,4,5,6,7,8,9,10]
One way to interpret that would be:
a = [1,2,3,4,5,6,7]
b = 8
c = [9]
d = 10
Another would be:
a = [1]
b = 2
c = [3,4,5,6,7,8,9]
d = 10
Yet another would be:
a = []
b = 1
c = [2,3,4,5,6,7,8,9]
d = 10
Python refuses to guess: It simply declares the code invalid.
Upvotes: 2