Python Set Tutorial with Examples

Python Sets

In Python, a Set represents one of the four fundamental data types designed to hold multiple items within a single variable. A Set is characterized by its lack of indexing and its unordered nature, comprising distinct elements that are unique. For instance, utilizing a set is an excellent choice for keeping track of employee IDs, as these identifiers must be unique and cannot be repeated.

Let us take a look at a simple example of a set.

Example

Example

# creating a Set

S = {202, 205, 204, 209, 207}

print(S)

Output:

Output

{209, 202, 204, 205, 207}

Explanation:

In the preceding example, we established a basic collection that contains several elements. It is evident that the elements within the initialized collection do not follow any specific order.

A set is classified as a mutable data type, signifying that we have the ability to add or remove data elements from it. Python Sets bear resemblance to mathematical sets, allowing us to execute operations such as intersection, union, symmetric difference, and various others.

Characteristics of Python Sets

Set in Python is a data type , which is:

  • Unordered: Sets do not maintain the order of how elements are stored in them.
  • Unindexed: We cannot access the data elements of sets.
  • No Duplicate Elements: Each data element in a set is unique.
  • Mutable (Changeable): Sets in Python allow modification of their elements after creation.
  • Creating a Set

Forming a set in Python is a straightforward and uncomplicated task. Python provides two methods to establish a set:

  • Utilizing curly braces
  • Employing the set function
  • Using Curly Braces

A collection can be formed by placing elements inside curly brackets '{}', with each element separated by commas.

Let’s examine a straightforward example that illustrates how to construct a set utilizing curly braces.

Example

Example

# simple example to create a set using curly braces

int_set = {12, 6, 7, 9, 11, 10}   # set of integers

print(int_set)

str_set = {'one', 'two', 'three', 'four', 'five'} # set of strings

print(str_set)

mixed_set = {12, 'logicpractice', 7.2, 6e2} # mixed set

print(mixed_set)

Output:

Output

{6, 7, 9, 10, 11, 12}

{'one', 'three', 'two', 'four', 'five'}

{600.0, 'logicpractice', 12, 7.2}

Explanation:

In this illustration, we have utilized curly braces to generate various kinds of sets. Additionally, it is evident that a set is capable of holding an arbitrary number of items of diverse types, such as integers, floats, tuples, strings, and so forth. However, it is important to note that a set is not able to accommodate mutable elements, including lists, sets, or dictionaries.

Using the set Function

Python provides a different method for generating a set through its built-in function named set. This function enables us to construct a set from an iterable that is provided as an argument.

The subsequent illustration demonstrates how to utilize the set function:

Example

Example

# simple example to create a set using set() function

# given list

int_list = [6, 8, 1, 3, 7, 10, 4]

# creating set using set() function

int_set = set(int_list)

print("Set 1:", int_set)

# creating an empty set

empty_set = set()

print("Set 2:", empty_set)

Output:

Output

Set 1: {1, 3, 4, 6, 7, 8, 10}

Set 2: set()

Explanation:

In the preceding example, the set function has been utilized to generate a set from a specified list. Additionally, we have formed an empty set by invoking the set function without passing any parameters.

Note: Creating an empty set is a bit tricky. Empty curly braces '{}' will make an empty dictionary in Python.

Accessing Elements of a Set

Given that sets are neither ordered nor indexed, it is not possible to access elements based on their position. Nonetheless, we can traverse a set using loops effectively.

Python Example to Access Element of a Set

Let us examine a straightforward example that demonstrates how to iterate over a set in Python.

Example

Example

# simple example to show how to iterate through a set

# given set

set_one = {11, 17, 12, 5, 7, 8}

print("Given Set:", set_one)

# iterating through the set using for loop

print("Iterating through the Set:")

for num in set_one:

  print(num)

Output:

Output

Given Set: {17, 5, 7, 8, 11, 12}

Iterating through the Set:

17

5

7

8

11

12

Explanation:

In this illustration, we have utilized the 'for' loop to traverse the elements present within the specified set.

Adding Elements to the Set

Python offers functions such as add and update for the purpose of incorporating elements into a set.

  • add: This function serves to insert a single item into the set.
  • update: This function is utilized to include several items into the set.
  • Python Set Example to Add Elements

Let's examine a straightforward example that demonstrates how to incorporate elements into a set in Python.

Example

Example

# simple example to show how to add elements to the set

# given set

subjects = {'physics', 'biology', 'chemistry'}

print("Given Set:", subjects)

# adding a single element to the set

subjects.add('maths')       # using add()

print("Updated Set (Added single element):", subjects)

# adding multiple elements to the set

subjects.update(['computer', 'english'])      # using update()

print("Update Set (Added Multiple elements):", subjects)

Output:

Output

Given Set: {'physics', 'biology', 'chemistry'}

Updated Set (Added single element): {'physics', 'biology', 'chemistry', 'maths'}

Update Set (Added Multiple elements): {'physics', 'chemistry', 'english', 'biology', 'computer', 'maths'}

Explanation:

In this illustration, we present a collection that contains three elements. Subsequently, we employed the add function to incorporate an additional element into the collection. Furthermore, we utilized the update function to introduce several new elements to the specified set.

Removing Elements from the Set

In Python, we can easily remove elements from a given set using methods like remove , discard , pop , and clear.

  • remove: This method allow us to remove a specific element from the set. It will raise a KeyError if the element is not found in the given set.
  • discard: This method is also used to remove a specified element from the set; however, it does not raise any error if the element is not found.
  • pop: This method is used to remove and returns a random element from the set.
  • clear: This method is used to remove all the elements from the given set.
  • Python Example to Remove Elements from the Set

Below is a straightforward illustration demonstrating how these methods function to eliminate elements from a set in Python.

Example

Example

# simple example to show how to remove elements from the set

# given set

subjects = {'physics', 'chemistry', 'english', 'biology', 'computer', 'maths'}

print("Given Set:", subjects)

# removing a specified element from the set

subjects.remove('maths')      # using remove()

print("Updated Set (Removed 'maths'):", subjects)

# removing a specified element from the set

subjects.discard('chemistry')      # using discard()

print("Updated Set (Removed 'chemistry'):", subjects)

# removing a random element from the set

subjects.pop()      # using pop()

print("Updated Set (Removed a random element'):", subjects)

# removing all elements from the set

subjects.clear()      # using clear()

print("Updated Set (Removed all elements):", subjects)

Output:

Output

Given Set: {'physics', 'chemistry', 'english', 'computer', 'biology', 'maths'}

Updated Set (Removed 'maths'): {'physics', 'chemistry', 'english', 'computer', 'biology'}

Updated Set (Removed 'chemistry'): {'physics', 'english', 'computer', 'biology'}

Updated Set (Removed a random element'): {'english', 'computer', 'biology'}

Updated Set (Removed all elements): set()

Explanation:

In this illustration, we present a collection made up of six distinct elements. Subsequently, we have employed the remove and discard functions to eliminate the designated elements from this collection. Following that, we utilized the pop method to extract a random element from the set. Finally, we applied the clear method to erase every element within the specified set, resulting in an empty set.

Set Operations in Python

Much like Set Theory in mathematics, sets in Python also facilitate a range of mathematical operations, including union, intersection, difference, symmetric difference, and additional operations.

Let’s explore several of these operations through illustrative examples.

Union of Sets

In mathematical language, the union of sets A and B is articulated as the set containing all elements that are part of either A, B, or both. This is represented by the notation A∪B.

Example

A∪B = {x: x ∈ A or x ∈ B}

As an example, let A be defined as {1, 2, 3} and let B be defined as {2, 3, 4, 5}. Consequently, the union of A and B, denoted A∪B, results in {1, 2, 3, 4, 5}.

In Python, we can achieve the union of sets by merging their elements while removing any duplicates, utilizing either the | operator or the union method.

Python Example for Union of Sets

Let's examine a straightforward illustration demonstrating how to perform the union of sets in Python.

Example

Example

# simple example on union of sets

set_A = {1, 2, 3}     # set A

print("Set A:", set_A)

set_B = {2, 3, 4, 5}  # set B

print("Set B:", set_B)

print("\nUnion of Sets A and B:")       # union of sets

print("Method 1:", set_A | set_B)       # using |

print("Method 2:", set_A.union(set_B))  # using union()

Output:

Output

Set A: {1, 2, 3}

Set B: {2, 3, 4, 5}

Union of Sets A and B:

Method 1: {1, 2, 3, 4, 5}

Method 2: {1, 2, 3, 4, 5}

Explanation:

In the example provided, we established two distinct sets and executed their union by utilizing both the | operator and the union method.

Intersection of Sets

In mathematical language, the intersection of two sets, A and B, is characterized as the collection of elements that are common to both A and B. This is represented by the notation A∩B.

Example

A∩B = {x: x ∈ A and x ∈ B}

For example, consider the sets A = {1, 2, 3} and B = {2, 3, 4, 5}. Consequently, the intersection of A and B, denoted as A∩B, results in the set {2, 3}.

In Python, we can likewise achieve the intersection of sets by utilizing the & operator or the intersection method, which will yield the elements that are shared between the two sets.

Example of Set Intersection in Python

Let's take a look at a straightforward illustration demonstrating how to find the intersection of sets in Python.

Example

Example

# simple example on intersection of sets

set_A = {1, 2, 3}     # set A

print("Set A:", set_A)

set_B = {2, 3, 4, 5}  # set B

print("Set B:", set_B)

print("\nIntersection of Sets A and B:")       # intersection of sets

print("Method 1:", set_A & set_B)       # using &

print("Method 2:", set_A.intersection(set_B))  # using intersection()

Output:

Output

Set A: {1, 2, 3}

Set B: {2, 3, 4, 5}

Intersection of Sets A and B:

Method 1: {2, 3}

Method 2: {2, 3}

Explanation:

In the preceding illustration, we established two sets and executed their intersection utilizing both the & operator and the intersection function.

Difference of Sets

In mathematical language, the difference between two sets A and B is characterized as the collection of all elements that are present in set A but absent in set B. This is represented by the notation A - B.

Example

A-B = {x: x ∈ A and x ∉ B}

For example, consider the sets A = {1, 2, 3} and B = {2, 3, 4, 5}. Consequently, the difference A - B results in {1}, while the difference B - A yields {4, 5}.

In a similar fashion within Python, one can compute the difference between sets utilizing the - operator or the difference method. This will yield the elements that are found in the first set and are absent in the second set.

Python Example to Show the Difference of Sets

Let's explore a straightforward illustration that demonstrates the concept of set difference in Python.

Example

Example

# simple example on difference of sets

set_A = {1, 2, 3}     # set A

print("Set A:", set_A)

set_B = {2, 3, 4, 5}  # set B

print("Set B:", set_B)

print("\nA - B:")       # difference of sets

print("Method 1:", set_A - set_B)       # using -

print("Method 2:", set_A.difference(set_B))  # using difference()

print("\nB - A:")

print("Method 1:", set_B - set_A)       # using -

print("Method 2:", set_B.difference(set_A))  # using difference()

Output:

Output

Set A: {1, 2, 3}

Set B: {2, 3, 4, 5}

A - B:

Method 1: {1}

Method 2: {1}

B - A:

Method 1: {4, 5}

Method 2: {4, 5}

Explanation:

In the preceding illustration, we established two sets and executed the difference operation utilizing both the - operator and the difference method.

Set Comprehension

In Python, set comprehension provides a streamlined and efficient method for generating sets.

The subsequent example illustrates the functionality of set comprehension in Python:

Example

Example

# simple example on set comprehension

# creating a set of square of numbers

set_of_squares = {i**2 for i in range(6)}

print(set_of_squares)

# creating a set of cube of numbers

set_of_cubes = {i**3 for i in range(6)}

print(set_of_cubes)

Output:

Output

{0, 1, 4, 9, 16, 25}

{0, 1, 64, 8, 27, 125}

Explanation:

In the example provided, we utilized set comprehension to generate the intended set.

Frozenset in Python

A frozenset represents an unchangeable variant of a set, indicating that once it has been established, we are unable to add or eliminate elements from it. To generate a frozenset object, we can utilize Python's built-in function named frozenset.

Python Frozenset Example

Let's examine a straightforward illustration that demonstrates the process of creating a frozenset in Python.

Example

Example

# simple example to create a frozenset

# using the frozenset() function

imm_set = frozenset(['one', 'two', 'three', 'four', 'five'])

# printing results

print(imm_set)

print(type(imm_set))  # returning type

Output:

Output

frozenset({'two', 'one', 'five', 'four', 'three'})

<class 'frozenset'>

Explanation:

In the example provided, we utilized the frozenset function to generate a frozenset object from the given iterable. Frozensets are immutable objects that possess hashability, enabling their use as keys within dictionaries or as elements within other sets.

Conclusion

Python sets serve as an effective mechanism for managing groups of distinct elements. They offer efficient functionalities for checking membership, removing duplicates, and executing mathematical operations associated with sets. Gaining a solid understanding of sets and their features can significantly enhance one's ability to manipulate data and create algorithms using Python.

Python Sets - MCQs

  1. What is the main characteristic of a Python set?
  • It maintains the order of elements
  • It is immutable
  • It contains only unique elements
  • It allows duplicate elements
  1. Which of the following is the correct way of creating a set in Python
  • set_A =
  • set_A = {2, 4, 6}
  • set_A = (2, 4, 6)
  • set_A = "246"

Response: b) set_A = {2, 4, 6}

  1. What will the output be when executing the code provided?
  2. Example
    
    # python program
    
    set_A  = {2, 4, 4, 6, 8}
    
    print(len(set_A))
    
  • Error
  1. Which of these operations can be used to add an element to a set?
  • add
  • append
  • insert
  • extend

Response: a) add

  1. What will be the result produced by executing the subsequent code?
  2. Example
    
    # python program
    
    set_A = {2, 4, 6}
    
    set_B = {4, 8, 12}
    
    print(set_A - set_B)
    
  • {2, 6, 8, 12}
  • {8, 12}
  • {2, 6}

Input Required

This code uses input(). Please provide values below: