5.2.3 Removing Elements: remove() vs. discard()

Unit: Unit 5: Dictionaries and Sets • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Practice deleting elements using remove() and discard()
allowed_ports = {80, 443, 8080, 8443, 22}

# 1. Remove port 22 using remove()
allowed_ports.remove(22)

# 2. Safely discard a non-existent port (no crash, silent no-op)
allowed_ports.discard(3000)

# 3. Discard an existing port 8080
allowed_ports.discard(8080)

print("Remaining allowed ports sorted:", sorted(allowed_ports))
Open in Live Interactive Python Sandbox →