1. Tuple unpacking and decompression sequence assignment
Any sequence (or an iterative object) can be extracted and assigned to multiple variables by a simple assignment statement. The only prerequisite is that the number of variables must be the same as the number of elements in the sequence.
1. Parallel Assignment:
>>> x = (1, 2>>> A, b = x #>>> a1>>> b
2
2. Use the * operator to disassemble an iterative object as a function parameter:
>>> Divmod (8) # 20 for the remainder of 8, 2 * 8 + 4 = =(2, 4 >>> t = (, 8)>>> ; Divmod (*t) (2, 4>>> quotient, remainder = divmod (*>>> Quotient, Remainder # quotient and remainder (2, 4)
3. Use *args in the function to get an indeterminate number of parameters:
>>> A, B, *rest = range (5)>>>1, [2, 3, 4>>> A, b, *rest = range (3
)>>>
1, [2
>>> A, b, *rest = range (2
>>>
1, [])
4. In parallel assignments, the * prefix can only be used in front of a variable name, but this variable may appear anywhere in the assignment expression:
>>> A, *body, C, d = Range (5>>> A, body, C, D (0, [1, 2], 3, 4>>> ; *head, B, c, d = Range (5>>>1], 2, 3, 4)
.
Fluent Python and Cookbook Learning Notes (ii)