Intermediate โข Python
Tuples & Sets
๐ฆ What is a Tuple?
A tuple is like a list, but it uses round brackets ( ) instead of square brackets. Just like a list, you can get items using their index, starting at 0. Tuples are great for things that belong together, like the x and y position of a point on a map.
point = (3, 7)
print(point)
print(point[0])
print(point[1])
print(len(point))(3, 7) 3 7 2
๐ Everything in Tuples & Sets
Meet two new ways to group things together: tuples, which never change, and sets, which never have repeats. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
๐ฆ What is a Tuple?
A tuple is like a list, but it uses round brackets ( ) instead of square brackets. Just like a list, you can get items using their index, starting at 0. Tuples are great for things that belong together, like the x and y position of a point on a map.
point = (3, 7) print(point) print(point[0]) print(point[1]) print(len(point))๐ Tuples Cannot Change
Once a tuple is made, you cannot change, add, or remove its items. We say tuples are immutable, which just means they cannot be changed. This keeps important data safe, like the days of the week, which should never change by accident.
days = ("Mon", "Tue", "Wed") print(days[2]) try: days[0] = "Sun" except TypeError: print("Oops! Tuples cannot be changed.")๐ Unpacking Tuples
Unpacking means taking the items out of a tuple and putting each one into its own variable in one line. The number of variables must match the number of items. You can also loop over a tuple with a for loop, just like a list.
hero = ("Luna", 11, "Wizard") name, age, job = hero print(name) print(age) print(job) for colour in ("red", "green"): print(colour)๐งบ What is a Set?
A set is a group of items inside curly brackets { }. A set never keeps duplicates, so if the same item appears twice, it is only stored once. Sets do not keep items in order, so we use sorted() to print them neatly in order.
numbers = {3, 1, 3, 2, 1} print(sorted(numbers)) print(len(numbers)) pets = {"cat", "dog", "cat"} print(len(pets))โ Adding, Removing and Checking
You can put new items into a set with add() and take them out with remove(). If you add something that is already there, nothing changes. The in keyword tells you if an item is in the set, giving True or False.
fruits = {"apple", "banana"} fruits.add("mango") fruits.add("apple") fruits.remove("banana") print(sorted(fruits)) print("mango" in fruits) print("banana" in fruits)๐ค Removing Duplicates and Combining Sets
Turning a list into a set with set() is a quick way to remove repeats. You can also combine sets: | gives every item from both sets, and & gives only the items that are in both. This is useful for finding things friends have in common!
votes = ["pizza", "tacos", "pizza", "pasta", "tacos"] print(sorted(set(votes))) amy = {"football", "chess", "art"} ben = {"chess", "art", "music"} print(sorted(amy | ben)) print(sorted(amy & ben))
