Skip to main content

Python Tutorial 4.4 - Sets in Python

Welcome to the “Sets in Python” tutorial!


Overview

Sets are unordered collections of unique elements, useful for membership testing and set operations.

Creating Sets

fruits = {"apple", "banana", "cherry"}
empty = set()

Common Operations

  • Adding/Removing Items:
    fruits.add("date")
    fruits.remove("banana")
    
  • Membership Testing:
    "apple" in fruits  # True
    
  • Set Operations:
    a = {1, 2, 3}
    b = {3, 4, 5}
    print(a.union(b))       # {1,2,3,4,5}
    print(a.intersection(b))# {3}
    print(a.difference(b))  # {1,2}
    

Key Takeaways

  • Sets enforce uniqueness.
  • Perfect for mathematical set operations.
  • Not indexed—cannot slice or access by position.

Happy coding!

Comments