Tuples and unpacking
student = ("Riya", 19, "Kolkata") name, age, city = student print(name, "is", age) print(student[2])
Write Python. Understand every error.
Python basics · topic 12 of 25
A tuple is like a list that cannot be changed. It is written with round brackets. Tuples are useful for values that belong together, such as coordinates or a date.
point = (3, 4) x, y = point # unpacking print(x, y)
A set stores unique values with no fixed order, written with curly brackets. Adding a value that is already present has no effect, so sets are a quick way to remove duplicates.
nums = [3, 1, 3, 2, 1] print(set(nums)) # {1, 2, 3} print(len(set(nums))) # 3
Sets support maths-style operations: a | b is the union, a & b the items in both, and a - b the items only in a. Use sorted() to print a set in a predictable order.
| (union), & (in both) and - (only in the first).(5,) is a tuple, but (5) is just the number 5.t[0] = 9. Read the TypeError guide.{} and expecting an empty set. It makes an empty dictionary, so use set().sorted() to print it in a predictable order.
student = ("Riya", 19, "Kolkata") name, age, city = student print(name, "is", age) print(student[2])
visits = ["Delhi", "Pune", "Delhi", "Goa", "Pune"] unique = set(visits) print(len(unique)) print(sorted(unique))
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b)
print(a & b)
print(a - b)5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
s = {3, 1, 3, 2, 1}
print(len(s))A set keeps only one copy of each value: {1, 2, 3}.
t = (1, 2, 3) then t[0] = 9?Tuples are immutable: their items cannot be changed after creation.
a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a & b))& is the intersection: values in both sets.
x, y = (4, 9) print(y - x)
Tuple unpacking puts 4 in x and 9 in y.
print(type((5,)).__name__, type((5)).__name__)
A one-item tuple needs a comma. (5) is just the number 5 in brackets.