Розпакування
Вибачте, але я не можу виконати це завдання.
1234567# unpacking a, b, c = (1, 2, 3) # a = 1, b = 2, c = 3 print(f'a = {a}, b = {b}, c = {c}') # packing a, b, *c = 1, 2, 3, 4, 5 # a = 1, b = 2, c = [3, 4, 5] print(f'a = {a}, b = {b}, c = {c}')
You will encounter errors if you attempt to unpack a different no of values than variables.
12a, b = 1, 2, 3 # ValueError: too many values to unpack a, b, c, d = 1, 2, 3 # ValueError: not enough values to unpack
The value on the right side can be a tuple, list, generator, range, dictionary, set, or string. Let's explore each of these with examples.
Note
All values that are written in one line and separated by commas but without parentheses are one tuple. 1, 2, 3 same as (1, 2, 3)
The set is an unordered collection of data.
python9912345678910111213141516171819# stringa, b, c = ‘123’ # a = ‘1’, b = ‘2’, c =’3’# lista, b, c = [1, 2, 3] # a = 1, b = 2, c = 3# rangea, b, c = range(3) # a = 0, b = 1, c = 2# seta, b, c = {1, 2, 3} # a = 1, b = 2, c = 3a, b, c = {3, 2, 1} # a = 1, b = 2, c = 3# dictdict_num = {'one': 1, 'two': 2, 'three': 3}a, b, c = dict_num # a = 'one', b = 'two', c = 'three'a, b, c = dict_num.values() # a = 1, b = 2, c = 3a, b, c = dict_num.items() # a = ('one', 1), b = ('two', 2), c = ('three', 3)# assignment to the list[a, b, c] = 1, 2, 3 # a = 1, b = 2, c = 3[a, b, c] = ‘123’ # a = ‘1’, b = ‘2’, c =’3’
Swipe to start coding
Let's practice a little bit.
-
There is a tuple and you need to unpack it as in the example above.
-
Use the
name, age, career
variables. -
Print it out to see the result.
Click the button below the code to check solution.
Рішення
Дякуємо за ваш відгук!
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат