no_snack = ()
print(no_snack)
snack = ("chips",)
print(snack)
snack_calories = {"chips": 140, "popcorn": 80, "nuts": 190}
items = list(snack_calories.items())
print(items)()
('chips',)
[('chips', 140), ('popcorn', 80), ('nuts', 190)]
tuple is a builtin type for immutable, ordered sequences()
('chips',)
[('chips', 140), ('popcorn', 80), ('nuts', 190)]
Peanut butter
('Peanut butter',)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 2 1 pair = ("Chocolate", "Peanut Butter") ----> 2 pair[0] = "Honey" TypeError: 'tuple' object does not support item assignment
Peanut Butter and Jelly
favourite_snacks = {
"salty": ("pretzels", 100),
"sweet": ("cookies", 180),
"veggie": ("carrots", 20),
}
((type1, (name1, cals1)), (type2, (name2, cals2)), (type3, (name3, cals3))) = (
favourite_snacks.items()
)
print(f"Favourite {type1} is {name1} with {cals1} calories")
print(f"Favourite {type2} is {name2} with {cals2} calories")
print(f"Favourite {type3} is {name3} with {cals3} calories")Favourite salty is pretzels with 100 calories
Favourite sweet is cookies with 180 calories
Favourite veggie is carrots with 20 calories
['arugula', 'bacon', 'carrots', 'pretzels']
['arugula', 'bacon', 'carrots', 'pretzels']
for loop expressions, e.g.1: bacon as 350 calories
2: donut as 240 calories
3: muffin as 190 calories
This is the classic example of pythonic
Short, but clear to see what is happening
Unpacking can also be used for
Unpacking does not work for assignment expressions
Requires you to be careful with your data structure to ensure the pattern matching works