Skip to main content

Introduction to Python Sets

Python Sets

A set is an unordered collection of unique elements.

Sets are defined by enclosing the elements in curly braces {} or by using the set() constructor.

Sets can only contain immutable elements such as numbers, strings, or tuples, but not lists or other sets.

Here's an example of a set in Python:

fruits = {"apple", "banana", "orange"}

Creating a Set

You can create a set by enclosing elements in curly braces or by using the set() constructor.

fruits = {"apple", "banana", "orange"}  # Using curly braces
numbers = set([1, 2, 3, 4, 5]) # Using the set() constructor

Set Operations

Sets support various operations such as union, intersection, difference, and symmetric difference.

  • Union (|): Returns a new set that contains all unique elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
  • Intersection (&): Returns a new set that contains elements present in both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

intersection_set = set1 & set2
print(intersection_set) # Output: {3}
  • Difference (-): Returns a new set that contains elements present in the first set but not in the second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

difference_set = set1 - set2
print(difference_set) # Output: {1, 2}
  • Symmetric Difference (^): Returns a new set that contains elements present in either set, but not both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # Output: {1, 2, 4, 5}

Set Methods

Sets have several built-in methods that you can use, such as add(), remove(), discard(), pop(), clear(), copy(), and more.

fruits = {"apple", "banana", "orange"}

fruits.add("kiwi") # Add an element to the set
print(fruits) # Output: {"apple", "banana", "orange", "kiwi"}

fruits.remove("banana") # Remove an element from the set
print(fruits) # Output: {"apple", "orange", "kiwi"}

fruits.discard("kiwi") # Remove an element if it exists, without raising an error
print(fruits) # Output: {"apple", "orange"}

fruits.clear() # Remove all elements from the set
print(fruits) # Output: set()

Checking Set Membership

You can check if an element exists in a set using the in operator. It returns True if the element is found in the set and False otherwise.

fruits = {"apple", "banana", "orange"}

print("banana" in fruits) # Output: True
print("kiwi" in fruits) # Output: False