Näited¶
Pythonis kasutatakse tihti ennikut muutujate pakkimiseks:
fruits = "apple", "orange", "pear" # Tuple packing
f0, f1, f2 = fruits # Tuple unpacking
# f0 -> apple
# f1 -> orange
# f2 -> pear
cities = "London", "Ottawa", "Bristol", "New York", "Oslo"
uk, ca, *other_cities, nor = cities # The * operator just before a variable takes logically rest of the values
# other_cities -> ['Bristol', 'New York']
uk2, *other_cities2 = cities
# other_cities2 -> ['Ottawa', 'Bristol', 'New York', 'Oslo']
Ennikut on hea kasutada, kui on vaja, et funktsioon tagastaks mitu väärtust.
def hello():
return "Hi", "Tom" # Looks like several values are returned, actually it's just a tuple without parentheses
print(type(hello())) # -> <class 'tuple'>
h = hello()[0]
t = hello()[1]
print(h) # -> Hi
print(t) # -> Tom
# One liner with tuple unpacking -> h, t = hello()
# h = "Hi", t = "Tom"