#FutureSTEMLeaders - Wiingy's $2400 scholarship for School and College Students

Apply Now

Python

Python Sets

Written by Rahul Lath

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:

my_set = {1, 2, 3, 4, 5}

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:

my_set = set([1, 2, 3, 4, 5])

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:

my_set = 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:

my_set = {1, 2, 3, 4, 5} print(len(my_set)) # Output: 5

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:

my_set = {1, 2, 3, 4, 5} print(3 in my_set) # Output: True print(6 in my_set) # Output: False

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:

set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} # Using union operator union_set = set1 | set2 print(union_set) # Output: {1, 2, 3, 4, 5, 6} # Using intersection method intersection_set = set1.intersection(set2) print(intersection_set) # Output: {3, 4} # Using difference operator difference_set = set1 - set2 print(difference_set) # Output: {1, 2} # Using symmetric difference method symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set) # Output: {1, 2, 5, 6} # Using subset operator print(set1 < set2) # Output: False # Using issubset method print(set1.issubset(set2)) # Output: False # Using disjoint operator print(set1.isdisjoint(set2)) # Output: False

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.

my_set = {1, 2, 3} my_set.add(4) print(my_set) # Output: {1, 2, 3, 4}

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.

my_set = {1, 2, 3} my_set.remove(2) print(my_set) # Output: {1, 3}

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.

my_set = {1, 2, 3} my_set.update({3, 4, 5}) print(my_set) # Output: {1, 2, 3, 4, 5}

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.

 
my_set = {1, 2, 3} my_set.clear() print(my_set) # Output: 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:

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.
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 |= set2 print(set1) # Output: {1, 2, 3, 4, 5}
  1. Intersection assignment operator (&=): The intersection assignment operator keeps only the elements that are common in both sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 &amp;= set2 print(set1) # Output: {3}
  1. Difference assignment operator (-=): The difference assignment operator removes the elements from the first set that are present in the second set.
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 -= set2 print(set1) # Output: {1, 2}
  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.
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 ^= set2 print(set1) # Output: {1, 2, 4, 5}

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.
set1 = {1, 2, 3} set2 = {3, 4, 5} set1.update(set2) print(set1) # Output: {1, 2, 3, 4, 5}
  1. intersection_update() method: The intersection_update() method keeps only the elements that are common in both sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} set1.intersection_update(set2) print(set1) # Output: {3}
  1. difference_update() method: The difference_update() method removes the elements from the first set that are present in the second set.
set1 = {1, 2, 3} 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.
set1 = {1, 2, 3} set2 = {3, 4, 5} set3 = set1.union(set2) print(set3) # Output: {1, 2, 3, 4, 5}
  1. The intersection() method returns a set containing only the common elements from both sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} set3 = set1.intersection(set2) print(set3) # Output: {3}
  1. The difference() method returns a set containing the elements that are present in the first set but not in the second set.
set1 = {1, 2, 3} set2 = {3, 4, 5} set3 = set1.difference(set2) print(set3) # Output: {1, 2}

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.
set1 = {1, 2, 3} set2 = {3, 4, 5} set3 = set1.symmetric_difference(set2) print(set3) # Output: {1, 2, 4, 5}
  1. The isdisjoint() method returns True if two sets have no common elements.
set1 = {1, 2, 3} set2 = {4, 5, 6} print(set1.isdisjoint(set2)) # Output: True

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.
set1 = {1, 2, 3} set2 = {1, 2} print(set2.issubset(set1)) # Output: True
  1. The issuperset() method returns True if a set contains all the elements of another set.
set1 = {1, 2, 3} set2 = {1, 2} print(set1.issuperset(set2)) # Output: True
  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.
set1 = {1, 2, 3} set2 = {1, 2} print(set2.ispropersubset(set1)) # Output: True

D. Copying a Set

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

set1 = {1, 2, 3} set2 = set1.copy() set3 = set(set1) print(set2) # Output: {1, 2, 3} print(set3) # Output: {1, 2, 3}

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.

fset = frozenset([1, 2, 3]) print(fset) # Output: frozenset({1, 2, 3})

B. Creating frozen sets

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

set1 = {1, 2, 3} fset = frozenset(set1) print(fset) # Output: frozenset({1, 2, 3})

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.

fset = frozenset([1, 2, 3]) d = {fset: 'hello'} print(d) # Output: {frozenset({1, 2, 3}): 'hello'}

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.

set1 = {x for x in range(10)} print(set1) # Output: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

B. Creating sets with set comprehensions

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

set1 = {x**2 for x in range(10)} print(set1) # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81} set2 = {x for x in set1 if x % 2 == 0} print(set2) # Output: {0, 64, 4, 36, 16, 8}

C. Using set comprehensions with conditionals

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

set1 = {x for x in range(10) if x % 2 == 0} print(set1) # Output: {0, 2, 4, 6, 8}

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.

list1 = [1, 2, 3, 2, 1, 4, 5] set1 = set(list1) list2 = list(set1) print(list2) # Output: [1, 2, 3, 4, 5]

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.

list1 = [1, 2, 3, 4, 5] list2 = [4, 5, 6, 7, 8] set1 = set(list1) set2 = set(list2) common = set1.intersection(set2) print(common) # Output: {4, 5}

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.

set1 = {1, 2, 3, 4, 5} if 3 in set1: print('3 is in the set') # Output: 3 is in the set

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.

set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} union = set1.union(set2) intersection = set1.intersection(set2) difference = set1.difference(set2) print(union) # Output: {1, 2, 3, 4, 5, 6, 7,8}

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

Rahul Lath

Reviewed by

Arpit Rankwar

Share article on

tutor Pic
tutor Pic