Popular

Data Science

Technology

Finance

Management

Future Tech

Internship Assurance

DevOps & Cloud Engineering

Python sets are a singular and important data type, which is useful in many different programming tasks. Sets store several items under one variable like lists and dictionaries. However, these sets are not arranged according to any order. Hence, the elements don’t appear in any particular order and they do not allow duplicate values. This makes them very useful for applications like membership testing, and removal of duplicates including mathematical operations such as union and intersection.

This blog will cover everything about Python sets you should know. We will begin with the basics such as what’s a set and its characteristics then we shall delve into set operations, and methods and even expose some mathematical operations with examples given.

A set in Python is a collection of unordered, unique items. Unlike lists or tuples, sets do not allow duplicate elements. This means that each item in a set is unique, making sets ideal for storing distinct values and performing membership tests.

Sets are defined using curly braces {} or the set() function. For example, {1, 2, 3} is a set containing the numbers 1, 2, and 3. You can also create an empty set using set(), but not {}, as the latter will create an empty dictionary. Sets are mutable, so you can add or remove items after creating them. However, the items themselves must be immutable, like numbers, strings, or tuples.

Here are some features of Python sets that we have discussed here in brief.

**Unordered:**The sequence is not maintained inside a set. Elements can occur in random ways.**Unique Elements:**There are no repeated values among the elements enclosed within a set.**Mutable:**After instantiation, it is possible to change a set e.g., add or remove elements from it.**Immutable Elements:**Only immutable objects can be included inside sets e.g., numbers, strings, or tuples but excluding lists or dictionaries.**Heterogeneous Elements:**A collection may include members from different data types such as integers, strings, etc.**Dynamic Size:**There is an increase or decrease in size depending on whether elements are added to it or removed from there respectively.**No Indexing or Slicing:**Unordered sequences cannot be indexed, sliced, etc. by these structures unless using other set functions like the disjoint method or other sequence-like behaviour.**Efficient Membership Testing:**The most efficient way to check if an element is present is using the ‘’in’’ operator.

Also Read: **Python Tutorial for Beginners **

Python provides various operations to work with sets. These operations include creating sets, adding elements, checking for element presence, and more.

You can create a set in Python using curly braces {} or the set() constructor. Creating a set with curly braces is straightforward and allows you to define the elements directly.

**Example:**

In the below example, my_set is created using curly braces and contains the elements 1, 2, and 3. The print() function displays the set.

**Output:**

The set() constructor can be used to create a set from any iterable, such as a list, string, or tuple. This method is useful when you want to convert another data type into a set.

**Example from a list:**

Here, list_set is created from a list [1, 2, 3, 4] using the set() constructor. The print() function displays the set, showing the unique elements.

**Output:**

**Example from a string:**

In this example, string_set is created from the string “hello”. The set() constructor converts the string into a set of unique characters. The print() function shows the unique characters in the set.

**Output:**

**Example of creating an empty set:**

Creating an empty set requires using the set() constructor, as using {} will create an empty dictionary.

In this example, empty_set is created using the set() constructor, resulting in an empty set. The print() function confirms this by displaying set().

**Output:**

You can add elements to a set using the add() method for single elements or the update() method for multiple elements. These methods allow you to modify the set after its creation.

**Example**

In this example, the add() method adds the element 4 to my_set. The print() function displays the updated set, which now includes the new element.

**Output:**

**Example**

In this example, the update() method adds the elements 4, 5, and 6 to my_set. The print() function displays the updated set with the new elements included.

**Output:**

You can check if an element exists in a set using the ‘in’ keyword. This operation returns True if the element is present and False if it is not.

**Example**

In this example, the in keyword checks if the element 2 is in my_set, returning True. It also checks if the element 5 is in my_set, returning False since 5 is not present in the set.

**Output:**

You can remove elements from a set using the remove(), discard(), or pop() methods. Each method has its unique behaviour.

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

**Example**

In this example, the remove() method removes the element 3 from my_set. If you try to remove an element that does not exist, it will raise a KeyError.

**Output:**

The discard() method also removes a specified element from the set, but it does not raise an error if the element is not found.

**Example:**

In this example, the discard() method removes the element 3 from my_set. Unlike remove(), it does not raise an error when trying to discard an element that is not in the set.

**Output:**

The pop() method removes and returns an arbitrary element from the set. If the set is empty, it raises a KeyError.

**Example:**

In this example, the pop() method removes and returns an arbitrary element from my_set. The print() function shows the removed element and the updated set.

**Output:**

Sets in Python are implemented using hash tables. This allows for fast membership testing and insertion/deletion operations. Each element in a set must be hashable, which means it must have a hash value that does not change during its lifetime.

When you add an element to a set, Python computes the hash of the element and uses this value to determine where to place the element in the internal hash table. This makes checking for membership (using the in keyword) very efficient, with an average time complexity of O(1).

You can find the number of elements in a set using the len() function.

**Example:**

In this example, the len() function returns the number of elements in my_set, which is 4.

**Output:**

You can loop through the elements of a set using a for loop. Since sets are unordered, the elements will be iterated in an arbitrary order.

**Example:**

In this example, the for loop iterates over each element in my_set, printing them one by one.

**Output:**

You can compare sets in Python using various comparison operators. These operators allow you to check for equality, inequality, and subset/superset relationships. Here is a table of the common comparison operators and their descriptions:

Operator |
Description |

== | Checks if two sets are equal |

!= | Checks if two sets are not equal |

< | Checks if the left set is a subset of the right set |

<= | Checks if the left set is a subset of the right set or equal to it |

> | Checks if the left set is a superset of the right set |

>= | Checks if the left set is a superset of the right set or equal to it |

Let’s see how these operators work with examples.

**Example of Equality (== and !=):**

The == operator checks if two sets have the same elements, while the != operator checks if they do not.

In this example, set1 and set2 are equal because they contain the same elements, while set1 and set3 are not equal.

**Example of Subset and Superset (<, <=, >, >=):**

The < operator checks if the left set is a proper subset of the right set. The <= operator checks if the left set is a subset of the right set or equal to it. Similarly, the > operator checks if the left set is a proper superset of the right set, and the >= operator checks if the left set is a superset of the right set or equal to it.

These comparisons help you understand the relationships between different sets, allowing you to perform various operations and checks effectively.

Internship Assurance

DevOps & Cloud Engineering

Python sets support several mathematical operations, such as union, intersection, difference, and symmetric difference. These operations help you to perform common set operations easily and efficiently.

The union operation combines the elements of two sets into one, excluding duplicates. You can use the union() method or the | operator.

**Using union() method:**

In this example, union_set contains all elements from both set1 and set2, excluding duplicates.

**Using | operator:**

Here, the | operator performs the same union operation, resulting in a set that contains all unique elements from both sets.

The intersection operation finds common elements between two sets. You can use the intersection() method or the & operator.

**Using intersection() method:**

In this example, intersection_set contains only the common element (3) between set1 and set2.

**Using & operator:**

The & operator performs the intersection operation, yielding a set with common elements from both sets.

The difference operation returns elements that are in the first set but not in the second set. You can use the difference() method or the – operator.

**Using difference() method:**

In this example, difference_set contains elements (1, 2) that are in set1 but not in set2.

**Using – operator:**

The – operator performs the difference operation, resulting in a set with elements from set1 that are not in set2.

The symmetric difference operation returns elements that are in either of the sets but not in both. You can use the symmetric_difference() method or the ^ operator.

**Using symmetric_difference() method:**

In this example, symmetric_difference_set contains elements (1, 2, 4, 5) that are in either set1 or set2 but not in both.

**Using ^ operator:**

The ^ operator performs the symmetric difference operation, yielding a set with elements that are in either of the sets but not in both.

Python sets come with a variety of built-in methods that allow you to perform different operations. These methods make it easy to manipulate and manage sets effectively.

Method |
Description |

add() | Adds a single element to the set |

update() | Adds multiple elements to the set |

remove() | Removes a specified element from the set |

discard() | Removes a specified element without raising an error |

pop() | Removes and returns an arbitrary element from the set |

clear() | Removes all elements from the set |

copy() | Returns a shallow copy of the set |

union() | Returns the union of sets |

intersection() | Returns the intersection of sets |

difference() | Returns the difference of sets |

symmetric_difference() | Returns the symmetric difference of sets |

issubset() | Checks if the set is a subset of another set |

issuperset() | Check if the set is a superset of another set |

isdisjoint() | Checks if two sets have no elements in common |

Let’s look at examples for a few of these methods to understand how they work.

**Example of clear():**

The clear() method removes all elements from the set, leaving it empty.

**Example of copy():**

Here, the copy() method creates a shallow copy of my_set and assigns it to copy_set. The print() function displays the copied set, which contains the same elements as my_set.

A frozen set is a type of set that is immutable, meaning once it is created, you cannot change its elements. Frozen sets are similar to regular sets but with the restriction that they cannot be modified after creation. This immutability makes frozen sets hashable, allowing them to be used as keys in dictionaries or elements of other sets.

You can create a frozen set using the frozenset() function.

You can create a frozen set from any iterable, such as a list or a string.

In this example, frozenset([1, 2, 3, 4]) creates a frozen set from a list, and frozenset(“hello”) creates a frozen set from a string. The print() function displays the elements of the frozen sets.

Since frozen sets are immutable and hashable, they can be used as keys in a dictionary.

In this example, frozen_set1 and frozen_set2 are used as keys in the dictionary my_dict. The print() function shows the dictionary with frozen sets as keys, each associated with a corresponding value.

Frozen sets provide a way to use sets in contexts where immutability is required, such as dictionary keys or elements of other sets.

Python sets are versatile and can solve various problems efficiently. Here are some common problems and their solutions using sets.

You can find the minimum and maximum values in a set using the min() and max() functions.

**Example:**

In this example, min(my_set) finds the smallest element in my_set, which is 1, and max(my_set) finds the largest element, which is 9. The print() function displays these values.

**Output:**

You can remove multiple elements from a set using the difference_update() method or a loop.

**Using difference_update() method:**

In this example, difference_update(elements_to_remove) removes the elements 2 and 3 from my_set. The print() function shows the updated set without these elements.

**Output:**

You can add multiple elements to a set using the update() method.

**Example:**

In this example, update(elements_to_add) adds the elements 4, 5, and 6 to my_set. The print() function shows the updated set with the new elements included.

**Output:**

These examples demonstrate how to solve common problems using Python sets, making your code more efficient and concise.

Python sets are powerful tools for handling collections of unique items. They provide efficient ways to perform membership testing, eliminate duplicates, and carry out mathematical operations. By understanding the basics of sets, their characteristics, and various operations, you can effectively use sets in your Python projects to solve complex problems with ease.

From creating sets to performing union, intersection, and difference operations, this guide has covered everything you need to know about Python sets. Equipped with this knowledge, you can enhance your programming skills and handle data more efficiently in your applications.

Book a free counselling session

Get a personalized career roadmap

Get tailored program recommendations

Explore industry trends and job opportunities

Programs tailored for your success

Popular

Data Science

Technology

Finance

Management

Future Tech

Upskill with expert articles

View all

Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved