Python Sets Cheat Sheet with Examples

Python Sets Cheat Sheet with Examples



1. What are Sets?

A Set is an unordered collection of unique items. Sets are used to store multiple items in a single variable, but unlike lists, they do not allow duplicate values and do not support indexing.

Key Features:

  • Unordered: Items have no defined order.
  • Unindexed: You cannot access items by referring to an index or a key.
  • No Duplicates: Duplicate values are automatically removed.

Example:


my_set = {"apple", "banana", "cherry", "apple"}
print(my_set)

Output:


{'banana', 'cherry', 'apple'}

(Note: "apple" appears only once, and the order may vary.)


2. Creating an Empty Set

There is a specific way to create an empty set versus an empty dictionary.

⚠️ Important Note:

Using curly braces {} creates an empty Dictionary, not a Set.

To create an empty Set, you must use the set() constructor.


# This creates a Dictionary
empty_dict = {} 
print(type(empty_dict))

# This creates a Set
empty_set = set()
print(type(empty_set))

3. Adding Items

To add one item to a set, use the add() method.

Example:


fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits)

Output:


{'apple', 'orange', 'banana'}

4. Removing Items: remove() vs discard()

There are two primary ways to remove items, but they behave differently if the item usually doesn't exist.

A. remove()

Removes the item. If the item does not exist, it will raise an error.


fruits = {"apple", "banana"}
fruits.remove("banana") # Works fine
# fruits.remove("cherry") # This would throw a KeyError!

B. discard()

Removes the item. If the item does not exist, it will NOT raise an error.


fruits = {"apple", "banana"}
fruits.discard("cherry") # No error, simply does nothing
print(fruits)

✅ Tip:

Use discard() if you want to avoid errors when the item might strictly not be in the set.


5. Copying a Set

To create a copy of a set, use the copy() method.

Example:


fruits = {"apple", "banana"}
x = fruits.copy()
print(x)

6. Set Operations (Maths)

Sets in Python allow you to perform mathematical set operations like Union, Intersection, and Difference.

A. Union (|)

Returns a new set containing all items from both sets.


set1 = {"a", "b", "c"}
set2 = {1, 2, 3}

# Method 1
set3 = set1.union(set2)

# Method 2
set4 = set1 | set2 

print(set3)

B. Intersection (&)

Returns a new set containing only items that are present in both sets.


set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

result = set1.intersection(set2)
print(result)

Output: {'apple'}

C. Difference (-)

Returns a set containing items that exists only in the first set, and not in the second set.


set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

result = set1.difference(set2)
print(result)

Output: {'banana', 'cherry'}


📚 Related Topics:


📌 Bookmark this blog or follow for updates!

👍 Liked this post? Share it with friends or leave a comment below!

Post a Comment

Do Leave Your Comments...

Previous Post Next Post

Contact Form