Banner Image

Python

Python Sets

Written by Rahul Lath

Updated on: 12 Aug 2024

Python Tutorials

1Python Overview2Python Tutorial: A Comprehensive Guide for Beginners3Python Keywords and Identifiers4Download and Installation Guide for Python5Python Syntax (With Examples)6Python Comments7Python Variables (With Examples)8Taking Input in Python9Output in Python10File Handling in Python (Files I/O)11Python Operators (With Examples)12Ternary Operators in Python13Operator Overloading in Python14Division Operators in Python15Input from Console in Python16Output Formatting in Python17Any All in Python18Difference between Python Equality and Identity Operators19Python Membership and Identity Operators20Python Data Types21Python Dictionary22Control Flow in Python23Python Arrays24Looping Techniques in Python25Chaining Comparison Operators in Python26Python Functions27Python Strings28Python Numbers29Python Sets30Python For Loops31Python While Loops32Python Break Statement:33Python Continue Statement34Python pass Statement35Args and Kwargs in Python36Python Generators37Python Lambda38Global and Local Variables in Python39Global Keyword in Python40Python Closures41Python Decorators42Memoization using Decorators in Python43Constructors in Python44Encapsulation in Python45Inheritance in Python46Polymorphism in Python47Class Method vs Static Method in Python48Python Exception Handling49First Class Functions in Python50Python Classes And Objects51Errors and Exceptions in Python52Built-In Exceptions in Python53Append to file in Python54File Handling in Python55Destructors in Python56User-Defined Exceptions in Python57Class or Static Variable in Python58Python Tuples59Reading File in Python60Writing File in Python61Opening and Closing Files in Python62NZEC error in Python63Operator Function64Webscraper Python Beautifulsoup65Python Pyramid Patterns66Python Start Patterns67Web Crawler in Python68Build a Python Youtube Downloader69Currency Convertor in Python70Python Website Blocker
tutor Pic

What are Python Sets?

Python sets are a grouping of distinct objects. It is a group of elements that is neither ordered nor immutable. The set() function or curly braces can be used to create sets. A set’s components can be of any data type, including strings, integers, and even other sets.

The fact that a set forbids duplicate elements is one of its primary characteristics. A set won’t change if an element is already there; adding it again won’t. Additionally, sets do not keep the elements they contain in any particular order. This means that the order in which the elements are added to the set does not matter.

B. Difference between sets and other data structures

Although sets resemble other data structures like lists and tuples, there are some significant differences between them. The biggest distinction is that lists and tuples support duplicate elements, whereas sets do not. Lists and tuples are ordered, whereas sets are unordered. Tuples are immutable, whereas sets are also mutable, meaning they can be changed after creation.

C. How sets are used in Python

In Python, sets are used to carry out set operations such as union, intersection, and difference. Algorithms and calculations in mathematics frequently use set operations. Duplicates can also be eliminated from a list or tuple using sets.

Creating Sets in Python

A. Literal notation

Sets can be created using curly braces {} with elements separated by commas. Here is an example of creating a set with integers:

B. Using the set() constructor

Another way to create a set is by using the set() constructor function. The constructor function can take any iterable as an argument and returns a set containing all the unique elements in the iterable. Here is an example of creating a set using the constructor function:

C. Creating an empty set

To create an empty set, you cannot use empty curly braces as they will be interpreted as an empty dictionary. Instead, you can use the set() constructor function to create an empty set:

Set Size and Membership

You can determine the size of a set by using the len() function. The len() function returns the number of elements in a set. Here is an example of using the len() function to determine the size of a set:

Checking if an element is in a set

You can check if an element is in a set by using the in keyword. The in keyword returns True if the element is in the set and False otherwise. Here is an example of checking if an element is in a set:

Operating on a Set

A. Operators vs. Methods

Sets support both operators and methods for performing operations on them. Operators are symbols that perform an operation on two or more sets, while methods are functions that are called on a single set to modify it or perform an operation on it.

B. Available Operators and Methods

The following are the available operators and methods for sets in Python:

  1. Union Operator (|) and union() method: The union operator and the union() method return a set containing all the elements from both sets.
  2. Intersection Operator (&) and intersection() method: The intersection operator and the intersection() method return a set containing only the elements that are common in both sets.
  3. Difference Operator (-) and difference() method: The difference operator and the difference() method return a set containing the elements that are in the first set but not in the second set.
  4. Symmetric Difference Operator (^) and symmetric_difference() method: The symmetric difference operator and the symmetric_difference() method return a set containing the elements that are in either of the sets but not in both.
  5. Subset Operator (<) and issubset() method: The subset operator and the issubset() method return True if the first set is a subset of the second set.
  6. Superset Operator (>) and issuperset() method: The superset operator and the issuperset() method return True if the first set is a superset of the second set.
  7. Disjoint Operator and isdisjoint() method: The disjoint operator and the isdisjoint() method return True if the two sets have no common elements.

C. Examples of using operators and methods

Here are some examples of using operators and methods with sets:

Modifying a Set

A. Adding an element to a set

To add an element to a set, you can use the add() method. The add() method adds an element to the set if it is not already present in the set.

B. Removing an element from a set

To remove an element from a set, you can use the remove() method. The remove() method removes the element from the set if it is present in the set, and raises a KeyError if the element is not in the set.

C. Updating a set with another set

To update a set with another set, you can use the update() method. The update() method adds all the elements from the given set(s) to the original set.

D. Clearing a set

To remove all the elements from a set, you can use the clear() method. The clear() method removes all the elements from the set and makes it an empty set.

 

Augmented Assignment Operators and Methods

Examples of using augmented assignment operators

Augmented assignment operators are shorthand notations for performing an operation and assigning the result back to the original variable. For example, the following statement is equivalent to x = x + 1:

The following are the available augmented assignment operators for sets in Python:

  1. Union assignment operator (|=): The union assignment operator adds all the elements from the second set to the first set.
  1. Intersection assignment operator (&=): The intersection assignment operator keeps only the elements that are common in both sets.
  1. Difference assignment operator (-=): The difference assignment operator removes the elements from the first set that are present in the second set.
  1. Symmetric difference assignment operator (^=): The symmetric difference assignment operator keeps only the elements that are in either of the sets but not in both.

B. Examples of using methods for augmented assignment

The following are the available methods for performing augmented assignment on sets in Python:

  1. update() method: The update() method adds all the elements from the given set(s) to the original set.
  1. intersection_update() method: The intersection_update() method keeps only the elements that are common in both sets.
  1. difference_update() method: The difference_update() method removes the elements from the first set that are present in the second set.

Other Methods for Modifying Sets

A. Intersection, Union, and Difference

Sets in Python have three methods for performing the basic set operations – union, intersection, and difference.

  1. The union() method returns a set containing all the distinct elements from both sets.
  1. The intersection() method returns a set containing only the common elements from both sets.
  1. The difference() method returns a set containing the elements that are present in the first set but not in the second set.

B. Symmetric Difference and Disjoint

Sets in Python have two methods for performing symmetric difference and disjoint operations.

  1. The symmetric_difference() method returns a set containing the elements that are in either of the sets but not in both.
  1. The isdisjoint() method returns True if two sets have no common elements.

C. Subsets, Supersets, and Proper Subsets

Sets in Python have three methods for checking if a set is a subset, superset, or proper subset of another set.

  1. The issubset() method returns True if all the elements of a set are present in another set.
  1. The issuperset() method returns True if a set contains all the elements of another set.
  1. The ispropersubset() method returns True if a set is a proper subset of another set, i.e., it is a subset but not equal.

D. Copying a Set

To create a copy of a set, you can use the copy() method or the set() constructor.

Frozen Sets

A. Definition of frozen sets

Frozen sets are immutable collections of unique elements that are hashable, which means they can be used as elements of a set, but they cannot be modified once they are created. Frozen sets are created using the frozenset() constructor.

B. Creating frozen sets

Frozen sets can be created from other sets or any iterable using the frozenset() constructor.

C. Differences between frozen sets and sets

Frozen sets differ from sets in that they are immutable and hashable, which means they can be used as keys in dictionaries and elements of other sets.

Since frozen sets cannot be modified, they do not have any methods for adding, removing, or updating elements like sets do.

Set Comprehensions

A. Basic syntax

Set comprehensions provide a concise way to create sets in Python. The basic syntax of a set comprehension is similar to that of a list comprehension, except that it is enclosed in curly braces instead of square brackets.

B. Creating sets with set comprehensions

Set comprehensions can be used to create sets from any iterable, including other sets.

C. Using set comprehensions with conditionals

Set comprehensions can also be used with conditionals to filter elements.

Applications of Sets in Python

A. Removing duplicates from a list

One common application of sets in Python is to remove duplicates from a list. We can easily convert a list to a set to remove duplicates, and then convert it back to a list if necessary.

B. Finding common elements in multiple lists

Sets can also be used to find common elements in multiple lists. We can convert each list to a set and then take the intersection of the sets to find the common elements.

C. Checking for membership in a set

Sets are also useful for checking if an element is in a collection. Since sets use hash tables for fast membership testing, they are very efficient for large collections.

D. Performing set operations on large datasets

Sets are also useful for performing set operations like union, intersection, and difference on large datasets. Since sets are implemented using hash tables, they are very efficient for these types of operations.

Conclusion

  • A set is an unordered collection of unique elements in Python.
  • Sets are defined using the set() constructor or with literal notation {}.
  • Sets are mutable, and their contents can be modified using a variety of methods.
  • Sets have built-in methods for performing operations like union, intersection, difference, and more.
  • Set comprehensions provide a concise way to create sets in Python.

Python sets provide a powerful and efficient way to work with collections of unique elements. They are useful in a variety of programming tasks, from removing duplicates to performing set operations on large datasets. Understanding how to create, modify, and operate on sets is an important part of becoming a proficient Python programmer.

FAQs:

Q: What are sets in Python?

A: Sets in Python are an unordered collection of unique elements. They are defined using the set() constructor or with literal notation {}.

Q: What are the 2 types of sets in Python?

A: There are two types of sets in Python: mutable sets and immutable sets (frozen sets). Mutable sets can be modified, while frozen sets cannot.

Q: What are Python sets good for?

A: Python sets are good for a variety of programming tasks, such as removing duplicates from a list, finding common elements in multiple lists, checking for membership in a set, and performing set operations on large datasets.

Q: Is {} a set in Python?

A: No, {} is not a set in Python. It is the literal notation for an empty dictionary. To create an empty set, you should use set() instead.

Written by by

Rahul Lath

Reviewed by by

Arpit Rankwar

Share article on

tutor Pic
tutor Pic