Reputation: 4268
I know Python has a powerful multi-assignment function, eg. we can do
a, b = 1, 2
a, (b, c) = 1, (2, 3)
and even
for a, (b, c) in [(1, (2, 3)), ]:
print a, b, c
But how is this implemented? Is it an syntactic sugar or something more complicated?
Upvotes: 0
Views: 102
Reputation: 10484
Tuple Assignment from "how to think like a computer scientist"
This helps me a lot when I tried to learn about python, it explains about tuple assignment and how you can think of as pack/unpack (doesn't have to be tuple, as long as on the left hand side is assignable and on the right hand side is iterable)
list = [0]*3
[list[0],list[1],list[2]] = {1:1,2:2,3:3}
list is now "[1,2,3]"
you probably already know this, but just to make it complete, tuple assignment also works for functions:
a,b,c = function_return_a_three_tuple()
so functions in python may look like they can return multiple values, but its a false claim, they simply return a tuple and the tuple assignment makes it look like functions in python is more powerful that other language.
Upvotes: 0
Reputation: 2729
It's called 'tuple unpacking' if you want to dig around for the details of it but it actually works for any iterable on the right hand side, with the constraint that the number of variables being assigned to must match the number of elements in the iterable. I wouldn't call it syntactic sugar for anything since it does happen at runtime - it's not somehow magically transformed into a sequence of individual assignment statements in advance.
Upvotes: 1