Назначение кортежа в Python означает процесс одновременного присвоения нескольких значений нескольким переменным с использованием кортежей. Вот несколько методов присвоения кортежей с примерами кода:
-
Базовое присвоение кортежа:
# Assigning values to variables using a tuple x, y = 10, 20 print(x) # Output: 10 print(y) # Output: 20
-
Замена переменных:
# Swapping the values of two variables using tuple assignment a = 5 b = 10 a, b = b, a print(a) # Output: 10 print(b) # Output: 5
-
Распаковка кортежа:
# Unpacking a tuple into multiple variables point = (3, 7) x, y = point print(x) # Output: 3 print(y) # Output: 7
-
Игнорирование значений:
# Ignoring specific values using tuple assignment x, _, z = (1, 2, 3) print(x) # Output: 1 print(z) # Output: 3
-
Расширенная распаковка:
# Using * to unpack remaining items in a tuple a, *b, c = (1, 2, 3, 4, 5) print(a) # Output: 1 print(b) # Output: [2, 3, 4] print(c) # Output: 5
-
Возврат нескольких значений из функции:
# Returning multiple values from a function using tuple assignment def get_name_and_age(): name = "John" age = 25 return name, age person_name, person_age = get_name_and_age() print(person_name) # Output: John print(person_age) # Output: 25