Home » Python Sets : A Tutorial

Python Sets : A Tutorial

Spring Framework Basics Video Course
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification

In Python, a set is an unordered collection of unique elements. Unlike lists or tuples, sets do not allow duplicate values, and the elements inside a set are not indexed, meaning there is no way to access items by position or order.

Sets are ideal for membership tests and removing duplicate entries from a collection.

This tutorial covers how to create sets, modify them, and perform set operations like union, intersection, and difference, along with practical examples.

1. Creating a Set

You can create a set by placing all elements inside curly braces {} or by using the built-in set() function.

Example: Creating a Set

# Example: Creating a set
my_set = {1, 2, 3, 4, 5}
print(my_set)  # Output: {1, 2, 3, 4, 5}

# Creating a set with mixed data types
mixed_set = {1, "hello", 3.14, True}
print(mixed_set)  # Output: {1, 3.14, 'hello', True}

In this example:

my_set is a set of integers.
mixed_set contains a mix of different data types, including an integer, string, float, and boolean.

Creating a Set Using set()

You can also create a set from other iterable objects like lists or strings using the set() function.

# Example: Creating a set from a list
my_list = [1, 2, 3, 4, 5, 5, 3]
unique_set = set(my_list)
print(unique_set)  # Output: {1, 2, 3, 4, 5}

In this example:

set(my_list) converts the list my_list to a set and removes the duplicate values.

2. Adding Elements to a Set

Sets are mutable, meaning you can add elements to an existing set using add() or update() methods.

Example: Adding Elements Using add()

# Example: Adding an element to a set
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}

In this example:

add(4) adds the element 4 to my_set.

Example: Adding Multiple Elements Using update()

# Example: Adding multiple elements using update()
my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

In this example:

update([4, 5, 6]) adds multiple elements to the set at once.

3. Removing Elements from a Set

You can remove elements from a set using remove(), discard(), or pop() methods.

Example: Removing Elements Using remove()

# Example: Removing an element using remove()
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set)  # Output: {1, 2, 4, 5}

In this example:

remove(3) removes the element 3 from the set. If the element is not found, it raises a KeyError.

Example: Removing Elements Using discard()

Unlike remove(), the discard() method removes the element if it exists but does not raise an error if the element is not found.

# Example: Removing an element using discard()
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set)  # Output: {1, 2, 4, 5}

# If the element does not exist, discard() does nothing
my_set.discard(10)
print(my_set)  # Output: {1, 2, 4, 5}

Example: Removing and Returning an Element Using pop()

The pop() method removes and returns a random element from the set.

# Example: Removing and returning an element using pop()
my_set = {1, 2, 3, 4, 5}
removed_element = my_set.pop()
print(removed_element)  # Output: (random element from the set)
print(my_set)           # Output: Set with one less element

In this example:

pop() removes a random element because sets are unordered.

4. Checking if an Element Exists in a Set

You can check if an element exists in a set using the in keyword.

Example: Checking Membership in a Set

# Example: Checking if an element exists in a set
my_set = {1, 2, 3, 4, 5}

print(3 in my_set)  # Output: True
print(6 in my_set)  # Output: False

In this example:

The in keyword checks if 3 exists in the set (True) and if 6 exists in the set (False).

5. Set Operations

Python provides several built-in set operations, including union, intersection, difference, and symmetric difference. These operations are useful when working with multiple sets.

Example: Union of Sets

The union of two sets returns a new set containing all elements from both sets (without duplicates).

# Example: Union of two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4, 5}

# You can also use the | operator for union
union_set = set1 | set2
print(union_set)  # Output: {1, 2, 3, 4, 5}

In this example:

union() or the | operator returns the union of set1 and set2.

Example: Intersection of Sets

The intersection of two sets returns a new set containing only the elements that are present in both sets.

# Example: Intersection of two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {3}

# You can also use the & operator for intersection
intersection_set = set1 & set2
print(intersection_set)  # Output: {3}

In this example:

intersection() or the & operator returns the intersection of set1 and set2.

Example: Difference of Sets

The difference of two sets returns a new set containing elements that are in the first set but not in the second.

# Example: Difference of two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

difference_set = set1.difference(set2)
print(difference_set)  # Output: {1, 2}

# You can also use the - operator for difference
difference_set = set1 - set2
print(difference_set)  # Output: {1, 2}

In this example:

difference() or the – operator returns the difference between set1 and set2 (i.e., elements in set1 but not in set2).

Example: Symmetric Difference of Sets

The symmetric difference of two sets returns a new set containing elements that are in either set, but not in both.

# Example: Symmetric difference of two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

symmetric_diff_set = set1.symmetric_difference(set2)
print(symmetric_diff_set)  # Output: {1, 2, 4, 5}

# You can also use the ^ operator for symmetric difference
symmetric_diff_set = set1 ^ set2
print(symmetric_diff_set)  # Output: {1, 2, 4, 5}

In this example:

symmetric_difference() or the ^ operator returns the symmetric difference between set1 and set2.

6. Subset and Superset

You can check if a set is a subset or superset of another set using issubset() and issuperset() methods.

Example: Checking Subset and Superset

# Example: Checking subset and superset
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

# Checking if set1 is a subset of set2
print(set1.issubset(set2))  # Output: True

# Checking if set2 is a superset of set1
print(set2.issuperset(set1))  # Output: True

In this example:

issubset() checks if set1 is a subset of set2.
issuperset() checks if set2 is a superset of set1.

7. Iterating Over a Set

You can iterate over the elements of a set using a for loop.

Example: Iterating Over a Set

# Example: Iterating over a set
my_set = {1, 2, 3, 4, 5}

for item in my_set:
    print(item)

In this example:

The for loop iterates over each element in the set and prints it.

8. Frozen Sets

A frozen set is an immutable version of a set. You can create a frozen set using the frozenset() function, and once created, you cannot modify it (i.e., no adding or removing elements).

Example: Creating a Frozen Set

# Example: Creating a frozen set
my_set = frozenset([1, 2, 3, 4, 5])
print(my_set)  # Output: frozenset({1, 2, 3, 4, 5})

# Attempting to modify the frozen set will raise an error
# my_set.add(6)  # This will raise AttributeError

In this example:

A frozen set is created from a list, and attempting to modify it will result in an AttributeError.

9. Set Comprehension

You can create sets using set comprehension, similar to list comprehensions.

Example: Set Comprehension

# Example: Set comprehension to create a set of squares
squares = {x**2 for x in range(1, 6)}
print(squares)  # Output: {1, 4, 9, 16, 25}

In this example:

A set comprehension is used to create a set of squares from 1 to 5.

Summary

A set is an unordered collection of unique elements in Python. You can add, remove, and perform various operations like union, intersection, and difference.
Sets are ideal for membership testing and eliminating duplicate values from a collection.
You can perform subset and superset checks, iterate over sets, and work with frozen sets for immutable collections.
Set comprehensions provide a concise way to create new sets.

By mastering Python sets, you can effectively handle collections of unique elements and perform powerful set operations in your programs.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More