• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

In Out Code

Your comprehensive guide to optimized code

  • Data Structures
  • Python
    • Control Flow
    • HackerRank
    • Input and Output
    • Modules
  • AWS

Python Sets | Expert Guide with Code Samples

You are here: Home / Data Structures / Python Sets | Expert Guide with Code Samples

May 23, 2019 by Daniel Andrews

What is a Python Set?

A Python set is an unordered and unindexed collection of comma-separated values, enclosed in curly brackets {}. Sets can contain items (elements) of different data types (string, integer, float, tuple, etc.).

Each element in a set must be unique and immutable. This means a set cannot have a list, set, or dictionary as its items, as these are mutable.

Sets themselves are mutable. This means you can delete existing items or add new ones. Frozenset and tuple would be better options if you need an immutable collection.

Python sets are useful for mathematical set operations, such as union and intersect.

This guide is designed to walk you through how to use Python sets efficiently, with clear, commented code samples.

  • Create a set
  • Add items to a set
  • Iterate a set
  • Update a set
  • Delete from a set
  • Test set membership
  • Compare sets
  • Set operators
  • Built-in functions
  • Set methods
  • Sets vs. frozensets
  • Errors and exceptions

Create a Set

There are 2 ways to create a set in Python:

  1. Using the set() constructor
  2. Placing a comma-separated collection of elements inside curly braces {}.

The main differences between using the set() constructor and using the curly braces {} are:

  1. The argument passed to set() is an iterable that will generate a list of elements to be stored in the set
  2. The structure of objects passed to the curly braces {} is preserved, even if the values are iterable (e.g. string)
1. Using the set() constructor
# Create a set of strings using the set() constructor
string_set = set(("val1","val2","val3","val4"))
print(string_set)

# Pass a single string to the set() constructor
a = "TestString"
print("set(a) = ", set(a))

# For comparison, pass a single string to the list() constructor
a = "TestString"
print("list(a) = ", list(a))
Output:
{'val3', 'val4', 'val2', 'val1'}
set(a) = {'t', 'g', 'e', 'S', 's', 'T', 'n', 'i', 'r'}
list(a) = ['T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g']

The output above shows how the list() constructor preserves the order of the string, whereas the set() constructor does not.

2. Using a comma-separated collection of elements
# Create a set of strings
string_set = {"val1","val2","val3"}
print(string_set)

# Create a set containing values of multiple data types
set1 = {1,"val1",4.55,(2,3,4,5)}
print(set1)
Output:
{'val3', 'val2', 'val1'}
{1, (2, 3, 4, 5), 4.55, 'val1'}
# Confirmation that an error is thrown when a mutable type (list) is used as a set element
set1 = {1,"val1",[1,2,3,4]}
print(set1)
Output:
Traceback (most recent call last):

  File "", line 1, in 
    set1 = {1,"val1",[1,2,3,4]}

TypeError: unhashable type: 'list'
# Confirmation that a set cannot contain duplicate items
set1 = {1,2,2,2,3,4}
print(set1)
Output:
{1, 2, 3, 4}
# Confirmation that creating a set using curly braces {} preserves the structure of the iterable
set1 = {"TestString"}
print(set1)
Output:
{'TestString'}
Creating an empty set

If you need to create an empty set, you can use set(). If you use {}, you will create an empty dictionary.

# Check that a dictionary is created when using {}
x = {}
print("type({}) =", type(x))

# Check that a set is created when using set()
x = set()
print("type(set()) =", type(x))
Output:
type({}) = class 'dict'
type(set()) = class 'set'

Add Items to a Set

There are 2 main methods to add items to a set in Python:

  1. add() method for adding single item
  2. update() method for adding multiple items
1. Using add()
# Adding a single element using add()
set1 = {1,2,3}
print("set1 =", set1)

set1.add(4)
print("set1.add(4) =", set1)
Output:
set1 = {1, 2, 3}
set1.add(4) = {1, 2, 3, 4}
2. Using update()
# Create 2 seperate sets
set1 = {1,2,3}
set2 = {5,6,7}

# Add the contents of set2 to set1 using update()
set1.update(set2)
print("set1 =", set1)

# Create set3 with different data types
set3 = {(8,9),10,"11"}

# Add the contents of set3 to set1 using update()
set1.update(set3)
print("\nAdded a tuple, int, and string to set1: \n", set1)
Output:
Set1 = {1, 2, 3, 5, 6, 7}

Added a tuple, int, and string to set1:
{(8, 9), 1, 2, 3, 5, 6, 7, 10, '11'}

Iterate a Set

Items in a set can be iterated over in many ways. Two of the easiest to remember are:

  1. Using a for loop
  2. Using comprehension
1. Using a for() loop
# Creating a single-item string set
set1 = set("Test") 
  
# Iterate using for loop 
print("for() loop of set('Test'):")
for s in set1: 
    print(s) 
    
# Creating a multi-item integer set
set1 = {1,4,5,3}
  
# Iterate using for loop 
print("\nfor() loop of {1,4,5,3}:")
for s in set1: 
    print(s)
Output:
for() loop of set('Test'):
e
t
s
T

for() loop of {1,4,5,3}:
1
3
4
5
2. Using comprehension
# Creating a single-item string set
set1 = set("Test") 
  
# Iterate using list-comprehension 
print("Comprehension of set('Test'):")
compSet = [print(s) for s in set1] 

# Creating a multi-item integer set
set2 = {1,4,5,3}
  
# Iterate using list-comprehension 
print("\nComprehension of {1,4,5,3}:")
compSet = [print(s) for s in set2] 
Output:
Comprehension of set('Test'):
e
t
s
T

Comprehension of {1,4,5,3}:
1
3
4
5

Update a Set

Sets are mutable, which means that once a set is created, its items cannot be modified. Indexing and slicing cannot be used to access elements, as sets are unordered and unindexed.


Delete from a Set

There are 5 methods to delete items from a set, or delete the set itself:

  1. discard() method. If the item does not exist, discard() will not raise an error
  2. remove() method. If the item does not exist, remove() will raise an error
  3. del keyword, deletes the set completely
  4. clear() method empties the set
  5. pop() method removes the last item. Sets are unordered, so no control over which item this is

The only difference between discard() and remove() is that remove() will raise an error if the item isn’t in the set, while discard() will not.

1. discard()
# Create and populate a set
set1 = {1,2,3,4,5}
print("set1 = ", set1)

# Attempt to discard an item that doesn't exist in the set
set1.discard(6) # Won't throw an error
print("set1 discard(6) = ", set1)

# Attempt to discard an item that does exist in the set
set1.discard(5)
print("set1 discard(5) = ", set1) # 5 has now been discarded
Output:
set1 =  {1, 2, 3, 4, 5}
set1 discard(6) =  {1, 2, 3, 4, 5}
set1 discard(5) =  {1, 2, 3, 4}
2. remove()
# Create and populate a set
set1 = {1,2,3,4,5}
print("set1 = ", set1)

# Attempt to remove an item that doesn't exist in the set
set1.remove(6) # Will throw a KeyError
print("set1 remove(6) = ", set1)

# Attempt to remove an item that does exist in the set
set1.remove(5)
print("set1 remove(5) = ", set1) # 5 has now been removed
Output:
set1 =  {1, 2, 3, 4, 5}

Traceback (most recent call last):

  File "", line 5, in 
    set1.remove(6) # Will throw a KeyError

KeyError: 6

set1 remove(5) =  {1, 2, 3, 4}
3. del

Whereas the clear() method removes all items but leaves the list available, the del keyword deletes the set completely.

# Create and populate a set
set1 = {1,2,3,4,5}
print("set1 = ", set1)

# Call del on the set and attempt to print the result
del set1
print("set1 = ", set1)
Output:
set1 =  {1, 2, 3, 4, 5}

Traceback (most recent call last):

  File "", line 6, in 
    print("set1 = ", set1)

NameError: name 'set1' is not defined
4. clear()

The clear() method can be used to remove all items from a set, but leave the set object itself still available.

# Create and populate a set
set1 = {"val1","val2","val3","val4"}
print("set1 = ", set1)

# Clear the set and print the remaining contents
set1.clear()
print("set1 = ", set1)
Output:
set1 =  {'val3', 'val4', 'val2', 'val1'}
set1 =  set()
5. pop()

Because sets are unordered, the pop() method will remove an item completely at random from the set. In comparison, using the pop() method on a list will always remove the most recently added item.

# Create and populate a set
set1 = {1,2,3,4,5,6}
print("set1 = ", set1)

# Pop() an element in the set
print("\nelement deleted by set1.pop() = ", set1.pop())
print("set1 = ", set1)

# Pop() another element in the set
print("\nelement deleted by set1.pop() = ", set1.pop())
print("set1 = ", set1)
Output:
set1 =  {1, 2, 3, 4, 5, 6}

element deleted by set1.pop() =  1
set1 =  {2, 3, 4, 5, 6}

element deleted by set1.pop() =  2
set1 =  {3, 4, 5, 6}

Test Set Membership

To check if a set contains a value, you can use the in and not in keywords.

Using the in keyword:
# Check membership of an integer in a set
set1 = {1,2,3,4}
print("set1 =", set1)
print("TRUE test: 1 is in set1 =", 1 in set1)
print("FALSE test: 6 is in set1 =", 6 in set1)

# Check membership of a string in a set
set1 = {"val1","val2","val3"}
print("set1 =", set1)
print("TRUE test: 'val1' is in set1 =", "val1" in set1)
print("FALSE test: 'val8' is in set1 =", "val8" in set1)
Output:
set1 = {1, 2, 3, 4}
TRUE test: 1 is in set1 = True
FALSE test: 6 is in set1 = False
set1 = {'val1', 'val2', 'val3'}
TRUE test: 'val1' is in set1 = True
FALSE test: 'val8' is in set1 = False
Using the not in keyword:
# Check membership of an integer not in a set
set1 = {1,2,3,4}
print("set1 =", set1)
print("TRUE test: 6 is not in set1 =", 6 not in set1)
print("FALSE test: 1 is in not set1 =", 1 not in set1)

# Check membership of a string not in a set
set1 = {"val1","val2","val3"}
print("set1 =", set1)
print("TRUE test: 'val8' is not in set1 =", "val8" not in set1)
print("FALSE test: 'val1' is not in set1 =", "val1" not in set1)
Output:
set1 = {1, 2, 3, 4}
TRUE test: 6 is not in set1 = True
FALSE test: 1 is in not set1 = False
set1 = {'val3', 'val1', 'val2'}
TRUE test: 'val8' is not in set1 = True
FALSE test: 'val1' is not in set1 = False

Compare Sets

  • Sets are equal if every element of each set is contained in the other
  • Set A is greater than Set B if Set A is a superset of set B
  • Set A is less than Set B if Set A is a subset of set B
# Create our test sets
set1 = {1,2,3,4}
set2 = {1,2,3,4}
set3 = {1,2,3,4,5}
set4 = {2,3,4}

print("set1 =", set1)
print("set2 =", set2)
print("set3 =", set3)
print("set4 =", set4)

# Check if set1 and set2 are equal (TRUE)
print("set1 is equal to set2 =", set1 == set2)

# Check if set1 and set3 are equal (FALSE)
print("set1 is equal to set3 =", set1 == set3)

# Check if set3 is greater than set2 (TRUE)
print("set3 is greater than set2 =", set3 > set2)

# Check if set2 is greater than set3 (FALSE)
print("set2 is greater than set3 =", set2 > set3)

# Check if set2 is less than set3 (TRUE)
print("set2 is less tan set3 =", set2 < set3)

# Check if set3 is less than set4 (FALSE)
print("set3 is less than set4 =", set3 < set4)
Output:
set1 = {1, 2, 3, 4}
set2 = {1, 2, 3, 4}
set3 = {1, 2, 3, 4, 5}
set4 = {2, 3, 4}
set1 is equal to set2 = True
set1 is equal to set3 = False
set3 is greater than set2 = True
set2 is greater than set3 = False
set2 is less tan set3 = True
set3 is less than set4 = False

Set Operators

  • | operator is the equivalent of using the union() method. A | B.
  • & operator is the equivalent of using the intersection() method. A & B.
  • - operator is the equivalent of using the difference() method. A - B.
  • ^ is the equivalent of using the symmetric_difference() method. A ^ B.
# Create our test sets
set1 = {1,2,3,4}
set2 = {5,6,7,8}
set3 = {7,8,9,10,11}

print("set1 =", set1)
print("set2 =", set2)
print("set3 =", set3)

# Union together set1 and set2 using the | operator
print("set1 | set2 =", set1 | set2)

# Check the intersection of set2 and set3 using the & operator
print("set2 & set3 =", set2 & set3)

# Check the difference between set3 and set2 using the - operator
print("set3 - set2 =", set3 - set2)

# Check the symmetric difference between set2 and set3 using the ^ operator
print("set2 ^ set3 =", set2 ^ set3)
Output:
set1 = {1, 2, 3, 4}
set2 = {8, 5, 6, 7}
set3 = {7, 8, 9, 10, 11}
set1 | set2 = {1, 2, 3, 4, 5, 6, 7, 8}
set2 & set3 = {8, 7}
set3 - set2 = {9, 10, 11}
set2 ^ set3 = {5, 6, 9, 10, 11}

Built-in Functions

Python sets can be used with a variety of in-built functions. This includes len(), min(), max() and sorted().

len() function

The len() function can be used to return how many items are in a set.

# Create and populate a set
set1 = {1,2,3,4,5}
print("The length of set1 =", len(set1))
Output:
The length of set1 = 5
min() function

The min() function returns the minimum value in a set. If the set contains strings, the shortest string will be returned. If there are multiple strings that match the minimum length (e.g. "ab" and "cd"), the min() function returns the lowest ascii combination that matches the minimum length in the set.

A TypeError will be returned if a set containing mixed data types (e.g. combination of strings and integers) to the min() function.

# Create and populate a set of integers
set1 = {1,2,3,4,5}
print("Minimum value in set1 =", min(set1))

# Create and populate a set of strings
set2 = {"ab","abcd","abcde"}
print("Minimum value in set2 =", min(set2))

# Create and populate a set of strings of equal length
set3 = {"ab","aa","ac"}
print("Minimum value in set3 =", min(set3))

# Create and populate a set of strings and integers, to test the TypeError
set4 = {5,1,"ab","abcd","a",6}
print("Minimum value in set4 =", min(set4))
Output:
Minimum value in set1 = 1
Minimum value in set2 = ab
Minimum value in set3 = aa
Traceback (most recent call last):
  File "main.py", line 15, in 
    print("Minimum value in set4 =", min(set4))
TypeError: '<' not supported between instances of 'str' and 'int'
max() function

The max() function returns the maximum value in a set. If the set contains strings, the longest string will be returned. If there are multiple strings that match the maximum length (e.g. "ab" and "cd"), the max() function returns the highest ascii combination that matches the maximum length in the set.

A TypeError will be returned if a set containing mixed data types (e.g. combination of strings and integers) to the max() function.

# Create and populate a set of integers
set1 = {1,2,3,4,5}
print("Maximum value in set1 =", max(set1))

# Create and populate a set of strings
set2 = {"ab","abcd","abcde"}
print("Maximum value in set2 =", max(set2))

# Create and populate a set of strings of equal length
set3 = {"ab","aa","ac"}
print("Maximum value in set3 =", max(set3))

# Create and populate a set of strings and integers, to test the TypeError
set4 = {5,1,"ab","abcd","a",6}
print("Maximum value in set4 =", max(set4))
Output:
Maximum value in set1 = 5
Maximum value in set2 = abcde
Maximum value in set3 = ac
Traceback (most recent call last):
  File "main.py", line 15, in 
    print("Maximum value in set4 =", max(set4))
TypeError: '>' not supported between instances of 'str' and 'int'
sorted() function

The sorted() function sorts the set into ascending order by default. To reverse the sort order, an additional parameter can be specified in the form: sorted(,reverse=True).

For strings, the sort is based on the combined ascii value of the characters.

# Create and populate a set of integers
set1 = {1,2,3,4,5}
print("set1 with sorted() applied =", sorted(set1))
print("set1 with sorted(,reverse=True) applied =", sorted(set1, reverse=True))

# Create and populate a set of strings
set2 = {"ab","abcd","abcde"}
print("set2 with sorted() applied =", sorted(set2))
print("set2 with sorted(,reverse=True) applied =", sorted(set2, reverse=True))

# Create and populate a set of strings of equal length
set3 = {"ab","aa","ac"}
print("set3 with sorted() applied =", sorted(set3))
print("set3 with sorted(,reverse=True) =", sorted(set3,reverse=True))

# Create and populate a set of strings and integers, to test the TypeError
set4 = {5,1,"ab","abcd","a",6}
print("set4 with sorted() applied =", sorted(set4))
Output:
set1 with sorted() applied = [1, 2, 3, 4, 5]
set1 with sorted(,reverse=True) applied = [5, 4, 3, 2, 1]
set2 with sorted() applied = ['ab', 'abcd', 'abcde']
set2 with sorted(,reverse=True) applied = ['abcde', 'abcd', 'ab']
set3 with sorted() applied = ['aa', 'ab', 'ac']
set3 with sorted(,reverse=True) = ['ac', 'ab', 'aa']
Traceback (most recent call last):
  File "main.py", line 18, in 
    print("set4 with sorted() applied =", sorted(set4))
TypeError: '<' not supported between instances of 'str' and 'int'
sum() function

The sum() function can be used to calculate the sum total of all elements in a set composed solely of numeric data types (integer, decimal, etc.).

If sum() is applied to a set that contains strings or other iterables, Python reports a TypeError due to unsupported operand types.

# Create a set of integers
int_set = {1,2,3,4,5}
print("int_set =", int_set)

# sum() the int_set elements
print("sum(int_set) =", sum(int_set))

# Create a set of decimals
dec_set = {1.2, 2.4, 3.5, 5.6}
print("dec_set =", dec_set)

# sum() the dec_set elements
print("sum(dec_set) =", sum(dec_set))

# Create a set of strings
str_set = {"a","b","c","d"}
print("str_set =", str_set)

# Attempt to sum() the str_set elements
print("sum(str_set) =", sum(str_set))
Output:
int_set = {1, 2, 3, 4, 5}
sum(int_set) = 15
dec_set = {1.2, 2.4, 3.5, 5.6}
sum(dec_set) = 12.7
str_set = {'d', 'c', 'a', 'b'}
Traceback (most recent call last):
  File "main.py", line 20, in 
    print("sum(str_set) =", sum(str_set))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Set Methods

Python sets support the following methods: add(), clear(), copy(), difference(), difference_update(), discard(), intersection(), intersection_update(), isdisjoint(), issubset(), issuperset(), pop(), remove(), symmetric_difference(), symmetric_difference_update(), union(), update().

MethodDescription
add()Adds a single value to an existing set.
clear()Delete all elements from a set.
copy()Create a new set by copying an existing one.
difference()Highlight the difference in elements between two sets.
difference_update()Updates the set by removing items found in others. Multiple sets can be passed to the method, by comma separating them inside the parentheses.
discard()Removes a specific element from a set. Does not raise exceptions if specified element does not exist.
intersection()Only returns values that appear in both sets.
intersection_update()Overwrites the set that calls the method so that it only contains similarities between the calling set and the iterable set.
isdisjoint()Returns a Boolean stating whether the set contents overlap with the specified iterable.
issubset()Returns a Boolean stating whether the set contents are contained within the specified iterable.
issuperset()Returns a Boolean stating whether the full contents of the specified iterable are contained within the set.
pop()Removes an element at random from the set.
remove()Removes a specified element from the set. Raises KeyError if item doesn't exist in set.
symmetric_difference()Returns a new set containing elements that are in the calling set or iterable, but not both.
symmetric_difference_update()Updates the set calling the method with the items that appear in either the calling set or iterable, but not both.
union()Returns a new set, containing a distinct list of the values from the set and the iterable combined.
update()Add multiple items to a set.
add()

The add() method is used to add a single value to an existing set.

# Create a test set
set1 = {1,2,3,4}
print("set1 =", set1)

# Add a new integer to the test set
print("set1.add(5) =", set1.add(5))
Output:
set1 = {1, 2, 3, 4}
set1.add(5) = None
clear()

The clear() method is used to delete all elements from a set.

# Create a test set
set1 = {"a","b","c"}
print("set1 =", set1)

# Clear set1
set1.clear()
print("set1.clear() =", set1)
Output:
set1 = {'a', 'c', 'b'}
set1.clear() = set()
copy()

The copy() method is used to create a copy of a set.

# Create a test set
set1 = {1,2,3,4,5}
print("set1 =", set1)

# Create a copy of set1 and assign to set2
set2 = set1.copy()
print("set1.copy() =", set2)
Output:
set1 = {1, 2, 3, 4, 5}
set1.copy() = {1, 2, 3, 4, 5}
difference()

The difference() method is used to highlight the difference in elements between two sets. e.g. x.difference(y) would return values that appeared in set x but not in set y.

Returns the resulting elements in a new set object.

# Create two sets, containing similarities and differences
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print("set1 =", set1)
print("set2 =", set2)

# Check for values that appear in set1 but not set2
print("set1.difference(set2) =", set1.difference(set2))

# Check for values that appear in set2 but not set1
print("set2.difference(set1) =", set2.difference(set1))
Output:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1.difference(set2) = {1, 2, 3}
set2.difference(set1) = {8, 6, 7}
difference_update()

The difference_update() method performs a similar role to the difference() method, but overwrites the set on the left to only contain differences.

# Create two sets, containing similarities and differences
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print("set1 =", set1)
print("set2 =", set2)

# Perform difference_update() between set1 and set2
set1.difference_update(set2)
print("set1.difference_update(set2) =", set1)

# Recreate our two sets
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}

# Perform difference_update() between set2 and set1
set2.difference_update(set1)
print("set2.difference_update(set1)) =", set2)
Output:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1.difference_update(set2) = {1, 2, 3}
set2.difference_update(set1)) = {6, 7, 8}
discard()

The discard() method removes a specific element from a set. Will not raise any exceptions or error if the element you attempt to discard does not exist in the set.

# Create a test set
set1 = {1,2,3,4}
print("set1 =", set1)

# Discard element with value of 4
set1.discard(4)
print("set1.discard(4) =", set1)
Output:
set1 = {1, 2, 3, 4}
set1.discard(4) = {1, 2, 3}
intersection()

The intersection() works in the opposite way to the difference() method, only returning values that appear in both sets.

# Create two sets, containing similarities and differences
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print("set1 =", set1)
print("set2 =", set2)

# Check for values that appear in set1 and set2
print("set1.intersection(set2) =", set1.intersection(set2))
Output:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1.intersection(set2) = {4, 5}
intersection_update()

The intersection_update() method performs a similar role to the intersection() method, but overwrites the set on the left to only contain similarities.

# Create two sets, containing similarities and differences
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print("set1 =", set1)
print("set2 =", set2)

# Perform intersection_update() between set1 and set2
set1.intersection_update(set2)
print("After set1.intersection_update(set2), set1 =", set1)
Output:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
After set1.intersection_update(set2), set1 = {4, 5}
isdisjoint()

The isdisjoint() method returns a Boolean stating whether the set contents overlap with the specified iterable.

Returns True if the intersection of the set and iterable is an empty set, or if the method is passed an empty iterable.

Syntax: set.isdisjoint(iterable)

# Create a test set
set1 = {1,2,3,4}
print("set1 =", set1)

# Check disjoint() against a list that overlaps set1 (FALSE)
print("set1.isdisjoint([1,2]) =", set1.isdisjoint([1,2]))

# Check disjoint() against a set that partially overlaps set1 (FALSE)
print("set1.isdisjoint({2,3,4}) =", set1.isdisjoint({2,3,4}))

# Check disjoint() against a set that doesn't overlap set1 (TRUE)
print("set1.isdisjoint({5,6,7} =", set1.isdisjoint({5,6,7}))

# Check disjoint() against an empty set (TRUE)
print("set1.isdisjoint(set()) =", set1.isdisjoint(set()))
Output:
set1 = {1, 2, 3, 4}
set1.isdisjoint([1,2]) = False
set1.isdisjoint({2,3,4}) = False
set1.isdisjoint({5,6,7} = True
set1.isdisjoint(set()) = True
issubset()

The issubset() method returns a Boolean stating whether the set contents are contained within the specified iterable. Returns False if the method is passed an empty iterable.

Syntax: set.isiterable(iterable)

# Create a test set
set1 = {1,2,3}
print("set1 =", set1)

# Check issubset() against a list that contains all values in set1 (TRUE)
print("set1.issubset([1,2,3,4,5]) =", set1.issubset([1,2,3,4,5]))

# Check issubset() against a set that contains all values in set1 (TRUE)
print("set1.issubset({0,1,2,3,4}) =", set1.issubset({0,1,2,3,4}))

# Check issubset() against a set that contains some of the values in set1 (FALSE)
print("set1.issubset({2,3,4,5}) =", set1.issubset({2,3,4,5}))

# Check issubset() against an empty set (FALSE)
print("set1.issubset(set()) =", set1.issubset(set()))
Output:
set1 = {1, 2, 3}
set1.issubset([1,2,3,4,5]) = True
set1.issubset({0,1,2,3,4}) = True
set1.issubset({2,3,4,5}) = False
set1.issubset(set()) = False
issuperset()

The issuperset() method returns a Boolean stating whether the full contents of the specified iterable are contained within the set. Returns True if the method is passed an empty iterable.

Syntax: set.issuperset(iterable)

# Create a test set
set1 = {1,2,3,4,5}
print("set1 =", set1)

# Check issuperset() against a list whose values are all in set1 (TRUE)
print("set1.issuperset([1,2,3]) =", set1.issuperset([1,2,3]))

# Check issuperset() against a set whose values are all in set1 (TRUE)
print("set1.issuperset({1,2,3}) =", set1.issuperset({1,2,3}))

# Check issuperset() against a set containing values not found in set1 (FALSE)
print("set1.issuperset({1,2,3,6}) =", set1.issuperset({1,2,3,6}))

# Check issuperset() against an empty set (TRUE)
print("set1.issuperset(set()) =", set1.issuperset(set()))
Output:
set1 = {1, 2, 3, 4, 5}
set1.issuperset([1,2,3]) = True
set1.issuperset({1,2,3}) = True
set1.issuperset({1,2,3,6}) = False
set1.issuperset(set()) = True
pop()

The pop() method removes an element at random from the set. Returns the element removed.

Syntax: set.pop()

# Create a test set
set1 = {1,2,3,4}
print("set1 =", set1)

# pop() set1 to remove a random element
print("set1.pop() =", set1.pop())
print("set1 =", set1)

# pop() set1 to remove another random element
print("set1.pop() =", set1.pop())
print("set1 =", set1)
Output:
set1 = {1, 2, 3, 4}
set1.pop() = 1
set1 = {2, 3, 4}
set1.pop() = 2
set1 = {3, 4}
remove()

The remove() method removes a specified element from the set. Returns None.

Syntax: set.remove(x)

# Create a test set
set1 = {1,2,3,4}
print("set1 =", set1)

# Remove 1 from set1
set1.remove(1)
print("set1 after set1.remove(1) =", set1)

# Attempt to remove 5 from set1
set1.remove(5)
Output:
set1 = {1, 2, 3, 4}
set1 after set1.remove(1) = {2, 3, 4}
Traceback (most recent call last):
  File "main.py", line 10, in 
    set1.remove(5)
KeyError: 5
symmetric_difference()

The symmetric_difference() method returns a new set containing elements that are in the calling set or iterable, but not both. The symmetric_difference() of an empty set against an empty set is an empty set.

Syntax: setA.symmetric_difference(setB)

# Create 2 test sets
set1 = {1,2,3,4}
set2 = {3,4,5,6}
print("set1 =", set1)
print("set2 =", set2)

# Check the symmetric_difference() between set1 and set2
print("set1.symmetric_difference(set2) =", set1.symmetric_difference(set2))

# Check the symmetric_difference() between set1 and an empty set
print("set1.symmetric_difference(set()) =", set1.symmetric_difference(set()))

# Check the symmetric_difference() between set() and set()
print("set().symmetric_difference(set()) =", set().symmetric_difference(set()))
Output:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.symmetric_difference(set2) = {1, 2, 5, 6}
set1.symmetric_difference(set()) = {1, 2, 3, 4}
set().symmetric_difference(set()) = set()
symmetric_difference_update()

The symmetric_difference_update() method updates the set calling the method with the items that appear in either the calling set or iterable, but not both.

Passing in an empty iterable will always return the full contents of the set that calls the method.

Syntax: set.symmetric_difference_update(iterable)

# Create a test set
set1 = {1,2,3,4}
set2 = {3,4,5,6}
print("set1 =", set1)
print("set2 =", set2)

# Update set1 with the symmetric_difference() of set1 and set2
set1.symmetric_difference_update(set2)
print("set1.symmetric_difference_update(set2) =", set1)

# Update set1 with the symmetric_difference() of set1 and an empty set
set1.symmetric_difference_update(set())
print("set1.symmetric_difference_update(set()) =", set1)
Output:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.symmetric_difference_update(set2) = {1, 2, 5, 6}
set1.symmetric_difference_update(set()) = {1, 2, 5, 6}
union()

The union() method returns a new set, containing a distinct list of the values from the set and the iterable combined.

Syntax: set.union(iterable)

# Create test sets
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print("set1 =", set1)
print("set2 =", set2)

# Attempt to union() set1 and set2
set3 = set1.union(set2)
print("set1.union(set2) =", set3)

# Attempt to union() set3 with an empty set
set4 = set3.union(set())
print("set3.union(set()) =", set3.union(set()))

# Attempt to union() set4 with a list iterable
set5 = set4.union([8,9,10,11])
print("set4.union([8,9,10,11]) =", set5)
Output:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1.union(set2) = {1, 2, 3, 4, 5, 6, 7, 8}
set3.union(set()) = {1, 2, 3, 4, 5, 6, 7, 8}
set4.union([8,9,10,11]) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
update()

The update() method allows you to add multiple new elements to a set. New elements are passed to the method in the form of an iterable.

Syntax: set.update(iterable)

# Create a test set
set1 = {1,2,3,4}
print("set1 =", set1)

# Update set1 with values held in a list
set1.update([5,6,7])
print("set1.update([5,6,7]) =", set1)

# Update set1 with values held in a set
set1.update({7,8,9})
print("set1.update({7,8,9}) =", set1)

# Attempt to update set1 with an empty set
set1.update(set())
print("set1.update(set()) =", set1)
Output:
set1 = {1, 2, 3, 4}
set1.update([5,6,7]) = {1, 2, 3, 4, 5, 6, 7}
set1.update({7,8,9}) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
set1.update(set()) = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Sets vs. Frozensets

The frozenset() method returns an immutable object, initialized with elements from the iterable passed in. Frozen set is the same as a Python set object, except for the fact that it's immutable. Elements of a standard set can be modified at any time, while elements of frozen set remains the same after creation.


Errors and Exceptions

  • Using the remove() method, a KeyError will be raised if you pass the method a value that doesn't exist in the set
  • Using the pop() method, a KeyError will be raised if the set is empty
  • TypeError from passing a tuple containing both strings and integers to functions such as min() and max().

Category iconData Structures Tag iconPython Sets

About Daniel Andrews

Passionate about all things data and cloud. Specializing in Python, AWS and DevOps, with a Masters degree in Data Science from City University, London, and a BSc in Computer Science.

Primary Sidebar

48-Hour Flash Sale. Online courses as low as $12.99

Categories

  • AWS (4)
  • Concepts (1)
  • Control Flow (1)
  • Data Structures (9)
  • HackerRank (1)
  • Input and Output (1)
  • LeetCode (1)
  • Modules (1)
  • Operators (1)
  • Python (2)
Udemy.com Homepage 300x250

Footer

Recent Posts

  • How to Setup Neo4j on AWS ECS (EC2)
  • How to Setup Neo4j on AWS EC2
  • How to List AWS S3 Bucket Names and Prefixes
  • Amazon Redshift Tutorial (AWS)
  • Big O: How to Calculate Time and Space Complexity

.