Python Access & Add Set Items
Set access tests whether an item is in a set. A set has no index numbers at all.
Check with in
The word in gives a True or False answer.
cities = {"Paris", "Rome", "Oslo"}
print("Rome" in cities)
print("Lima" in cities)Add one item
Use add() for a single new item.
cities = {"Paris", "Rome"}
cities.add("Oslo")
print(sorted(cities))Add many from a list
Use update() to add every item in a list.
cities = {"Paris"}
cities.update(["Rome", "Oslo"])
print(sorted(cities))Update from tuple and set
Update also accepts a tuple or a set.
warm = {"Rome"}
warm.update(("Oslo",), {"Paris"})
print(sorted(warm))Example
visited = {"Paris"}
visited.add("Berlin")
spring = ["Rome", "Paris", "Oslo"]
summer = ["Madrid", "Rome"]
visited.update(spring)
visited.update(summer)
print(sorted(visited))
print(len(visited))Key points
- Membership test: use in to ask if an item is in a set
- Use add() to add one item to a set
- Use update() to add many items at once
- Use update() with a list, a tuple, or another set
In this example, visited starts with only Paris. The add() call adds Berlin as one item. The first update() call adds the spring list. The second update() call adds the summer list. Repeats like Paris and Rome drop away. The sorted() call prints the five cities in a stable order.
Note
A set has no indexes, so cities[0] fails — test with in instead
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which line adds one item called "Oslo" to a set called cities?