Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Packing in Python: Grouping Multiple Values into a Single Variable | Mastering Packing and Unpacking in Python
Intermediate Python Techniques

bookPacking 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
copy
1
*a, *b, *c = 1, 2, 3
copy
question mark

Can you use more than one iterable unpacking operator in a single expression?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

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

bookPacking 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
copy
1
*a, *b, *c = 1, 2, 3
copy
question mark

Can you use more than one iterable unpacking operator in a single expression?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 2
some-alt