Lesson 46 +10 XP

Access, Add, and Remove Set Items

Access, Add, and Remove Set Items

You can't index a set, but you can still look inside, add to it, and remove from it.

Loop through a set

thisset = {"apple", "banana", "cherry"}
for x in thisset:
    print(x)

Check membership

print("banana" in thisset)  # True

Add one item with add

thisset.add("orange")

Add many with update

thisset.update(["orange", "mango", "grapes"])

update() accepts lists, tuples, sets, and dicts.

Remove with remove

thisset.remove("banana")

remove() raises a KeyError if the item doesn't exist.

Remove with discard

thisset.discard("banana")

discard() does NOT raise an error if the item is missing.

pop removes a random item

Sets have no order, so pop() removes an unpredictable item:

x = thisset.pop()

clear empties the set

thisset.clear()

The del keyword

del deletes the whole set.

TL;DR

  • Loop with for; check with in.
  • add() adds one; update() adds many.
  • remove() errors on missing; discard() doesn't.
  • pop() removes a random item; clear() empties.