Packing in Python: Grouping Multiple Values into a Single Variable
To pack multiple variables, you need to use the *
iterable unpacking operator. Simply place an asterisk *
before the variable, and it will pack any number of variables. Packing a variable is only possible within a tuple or a list.
python9123456789a, b, *c = 1, 2, 3, 4, 5 # a = 1, b= 2, c = [3, 4, 5]a, *b, c = 1, 2, 3, 4, 5 # a = 1, b = [2, 3, 4], c = 5a, b, *c = 1, 2 # a = 1, b = 2, c = []*a, b = 1, 2, 3 # a = [1, 2], b = 3*a, = 1, 2, 3 # a = [1, 2, 3](*a,) = 1, 2, 3 # a = [1, 2, 3][*a] = 1, 2, 3 # a = [1, 2, 3]*a = 1, 2, 3 # SyntaxError: starred assignment target must be in a list or tuple
But the SyntaxError will occur if to use more than one unpacking operator.
9
1
*a, *b = 1, 2, 3, 4
1*a, *b = 1, 2, 3, 4
9
1
*a, *b, *c = 1, 2, 3
1*a, *b, *c = 1, 2, 3
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 1. Hoofdstuk 2
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.