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

book
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.

python
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.

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

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 2

Vraag AI

expand
ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt