Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asterisks outside of function calls

I'm venturing into python and I had a question regarding asterisks. I know that they are used for arguments in function calls but I have seen snippets of code using them outside of function cards (say for example, in a tuple of 5 grades, unpacking them into variables such as:

first, *middle, last = grades

Whenever I try to use asterisks in this context/contexts out of a function call's arguments, I get invalid syntax in the interpreter. Am I missing something here?

like image 254
bluecat Avatar asked Jun 11 '13 13:06

bluecat


1 Answers

Python 3 added extended tuple unpacking with support for one wildcard, see PEP 3132:

*start, tail = ...
head, *middle, tail =  ...

See the assignment statements reference documentation:

If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be a sequence with at least as many items as there are targets in the target list, minus one. The first items of the sequence are assigned, from left to right, to the targets before the starred target. The final items of the sequence are assigned to the targets after the starred target. A list of the remaining items in the sequence is then assigned to the starred target (the list can be empty).

Use of an asterix in the lef-hand side (target list) of an assignment is a syntax error in Python 2.

like image 66
Martijn Pieters Avatar answered Oct 09 '22 10:10

Martijn Pieters