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.
a, 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 = 5
a, 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.
1*a, *b = 1, 2, 3, 4
1*a, *b, *c = 1, 2, 3
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Awesome!
Completion rate improved to 3.7
Packing in Python: Grouping Multiple Values into a Single Variable
Svep för att visa menyn
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.
a, 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 = 5
a, 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.
1*a, *b = 1, 2, 3, 4
1*a, *b, *c = 1, 2, 3
Tack för dina kommentarer!