← Back to Chapters

Python Sets

? Python Sets

? Quick Overview

A set in Python is an unordered collection of unique items. It automatically removes duplicates and is very efficient for membership testing and mathematical set operations.

? Key Concepts

  • Sets are unordered (no index access).
  • All elements inside a set must be unique.
  • Sets are mutable, meaning we can add or remove items.
  • Use {} or set() to create sets.

? Syntax / Theory

You can create sets using curly braces or the set() constructor. Duplicate values are automatically removed.

? Code Example — Creating Sets

? View Code Example
fruits = {"apple", "banana", "cherry"}
print(fruits)  # {'banana', 'apple', 'cherry'}

numbers = set([1, 2, 3, 4])
print(numbers) # {1, 2, 3, 4}

➕ Adding Items

? View Code Example
fruits.add("orange")
fruits.update(["kiwi", "mango"])
print(fruits)  # {'apple', 'banana', 'cherry', 'orange', 'kiwi', 'mango'}

❌ Removing Items

? View Code Example
fruits.remove("banana")
fruits.discard("pineapple")  # no error
print(fruits)  # {'apple', 'cherry', 'orange', 'kiwi', 'mango'}

? Live Output / Explanation

Set operations don’t guarantee order, so printed results may vary. Duplicates are removed automatically, and using discard() avoids errors when the item does not exist.

? Tips

  • Use sets when order doesn’t matter.
  • Great for fast membership testing like if x in my_set.
  • Use set operations like union, intersection, and difference for efficient comparisons.

? Practice

  • Create a set of numbers with duplicates and observe how duplicates are removed.
  • Add items using both add() and update().
  • Remove items using remove() and discard().
  • Test membership with the in operator.