In python, I can write something like this:
some_list = [(1, 2, 3), (3, 2, 1)]
for i, *args in some_list:
print(args)
I will get the next output:
[2, 3]
[2, 1]
When we use *args
as function arguments, it is unpacked into a tuple
.
Why do we receive a list
in this situation?
It is just a design decision. Making it a tuple
was debated in the PEP 3132, but rejected on usability grounds:
Make the starred target a tuple instead of a list. This would be consistent with a function's *args, but make further processing of the result harder.
Simlarly, making it of the same type as the iterable on the rhs of the assignment, was rejected:
Try to give the starred target the same type as the source iterable, for example, b in a, *b = 'hello' would be assigned the string 'ello'. This may seem nice, but is impossible to get right consistently with all iterables.
The very example of yours is listed in the same PEP under specification.
Some reasoning is found in the mailing list of that debate.
When dealing with an iterator, you don't know the length in advance, so the only way to get a tuple would be to produce a list first and then create a tuple from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With