Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele 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

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 2

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Awesome!

Completion rate improved to 3.7

bookPacking in Python: Grouping Multiple Values into a Single Variable

Pyyhkäise näyttääksesi valikon

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

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 2
some-alt