Home Python Python set update explained with examples

Python set update explained with examples

The Python set update() method adds items from another set to the current set (or any other iterable). Before adding the items of the given iterable to the called set, this function turns it into a set. For example, if we have a Set my_set: {6, 7, 8} and a List lis: [7, “code”], calling my_set.update(lis) will update Set my_set, and the elements of Set my_set will be {6, 7, 8, “code”} after the update.

Python set update

update() has the following syntax:


my_set is a set, and iterable can be of any type, including a list, set, dictionary, string, etc. The iterable’s elements are added to set A.

  • Parameters: Iterable (list, tuple, dictionary, etc.) parameters are accepted by this method.
  • Return Value: Nothing is returned; instead, the caller Set is updated.

Let’s look at another scenario:

my_set.update(iter1, iter2, iter3)

Set my_set now contains the items of iterable iter1, iter2, and iter3. The set.update() method is demonstrated in the following example.

nums_var = {6, 7, 8}
primeNums_var = {7, 8, 10, 12}

print("Updated set: ", nums_var)

Before we dive deep into performing set updates with examples, let us explore what sets are in Python and how to use them. If you’re new to Python, you’ve probably come across lists. But, in Python, have you heard of sets? We’ll look at what sets are, how to make them, and the many operations you can do on them in this section to quickly understand the following section.

In Python, what are sets?

Sets are similar to lists in Python, except that their elements are immutable (you can’t edit or mutate a set’s items after they’ve been declared). You can, however, add or remove elements from the set.

Let us try to summarize if it was confusing:

A set is a changeable, unordered collection of elements whose elements are immutable. Another feature of a set is that it can contain components of many sorts. It means that you can have a collection of numbers, strings, and even tuples in the same collection!

How to make a set

The built-in set () function is the most popular way to create a set in Python.

first_set_var = set(("chromebook", 32, (6, 7, 8)))

second_set_var = set("chromebook")

You can also use the curly brace syntax to build sets:

third_set_var = {"IBM", ("DELL", "HP")}

The set () function accepts an iterable as a parameter and returns a list of objects to be added to the set. The objects are placed into the set by the syntax {}. Whether you use the set () function or create a set, each element must be an immutable object, as you’ve probably noticed. If you try to add a list (a mutable object) to a set, you’ll get the following error:

incorrect_set _var= {"IBM", ("DELL", "HP")}

How to change the order of elements in a set

Sets are mutable, as we well know. It implies that you can add and remove elements from a set. Here’s an example of using the update() function to add elements to a set.

add_set_var = set((6, 7, 8, 9))


add_set_var.update(("piano", "guitar"))

When we try to add “piano” to the set again, though, nothing changes:


The latter is because Python sets cannot include duplicates. As a result, when we tried to add “cello” to the set again, Python detected that we were trying to add a duplicate element and did not update the set. It is one distinction between sets and lists. Here’s how you’d take elements out of a set:

sub_set_var = add_set_var

The remove(x) function removes a set’s element x. If x isn’t in the set, it throws a KeyError:


There are a few more methods for removing an element or elements from a set:

  • The discard(x) method removes x from the set, but it doesn’t throw an error if x isn’t in it.
  • The pop() method removes a random element from the set and returns it.
  • The clear() method clears a set of items.

Here, we conver some examples to help you understand:

m_set_var = set((6, 7, 8, 9))
m_set_var.discard(5) # no error raised even though '5' is not present in the set



set() operations in Python

Mathematical set operations like union, intersection, set difference, and the symmetric difference will likely come back to you if you remember your basic high school math. With Python sets, you can accomplish the same thing.

Set union

The set that contains all of the elements of both sets without duplicates is called the union of two sets. To determine the union of a Python set, use the union() method using the | syntax.

first_set_var = {6, 7, 8}
second_set_var = {8, 9, 10}
print(first_set_var | second_set_var) # using the | operator
Set intersection

Two sets’ intersection is the set that contains all of the sets’ shared items. To find the intersection of a Python set, use the intersection() method of the & operator.

first_set_var = {6, 7, 8, 9, 10, 11}
second_set_var = {9, 10, 11, 12, 13, 14}
print(first_set_var & second_set_var) # using the & operator
Set difference

The difference between the two sets is the set of all the elements in the first set that are not present in the second set. In Python, you’d use the difference () function or the – operator to accomplish this.

first_set_var = {6, 7, 8, 9, 10, 11}
second_set_var = {9, 10, 11, 12, 13, 14}

print(first_set_var - second_set_var) # using the - operator
print(second_set_var - first_set_var)
Set symmetric difference

The set containing all the elements either in the first set or the second set but not both is the symmetric difference between the two sets. In Python, you can use either the symmetric difference () function or the operator to accomplish this.

first_set_var = {6, 7, 8, 9, 10, 11}
second_set_var = {9, 10, 11, 12, 13, 14}
print(first_set_var ^ second_set_var) # using the ^ operator

How to change a set using operations

Each of the set () actions we described earlier is used to change the contents of an existing Python set.
You can update sets similarly to how you would update a variable using augmented assignment syntax like += or *=:

a_var = {6, 7, 8, 9, 10, 11}
b_var = {9, 10, 11, 12, 13, 14}

a_var.update(b_var) # a "union" operation

print(a_var &= b_var) # the "intersection" operation

a_var -= set((12, 13, 14)) # the "difference" operation

a_var ^= b_var # the "symmetric difference" operation

Python’s other set operations

These aren’t very frequent, but they help figure out how sets interact with one another.

  • If an is a subset of b, the a.issubset(b) method or the <= operator returns true.
  • If an is a superset of b, the a.issuperset(b) method or the >= operator returns true.
  • If there are no shared elements between sets a and b, the a.isdisjoint(b) method returns true.

Python frozen sets

Sets are unhashable since they are mutable. Hence they can’t be used as dictionary keys. You can get around this in Python by using a frozenset instead. It has all of the qualities of a set, except for being immutable (i.e., you can’t add or remove elements from the frozenset). It can also be used as the key in a dictionary because it is hashable.

The frozenset datatype has all of the methods of a set (such as difference (), symmetric_difference, and union). Still, it does not have any methods for adding or removing elements because it is immutable.

a_var = frozenset((6, 7, 8, 9))
b_var = frozenset((8, 9, 10, 11))

print(a_var.update(b_var)) # raises an error

It’s also as easy as 6, 7, 8 to use frozensets as dictionary keys:

b_var = frozenset(("w", "x", "y", "z"))
d_var = {a_var: "code", b_var: "underscored"}

After that brief refresher, let’s explore more about the set update with more elaborate examples.

Return value from update()

None is returned by the set update() function (returns nothing).

Example 1: Updating a Python set using update()

A_var = {'a', 'b'}
B_var = {6, 7, 8}

result = A_var.update(B_var)

print('A =', A_var)
print('result =', result)

Example 2: To Set, add elements from a string and a dictionary.

string_alphabet_vastring_alphabet_var = 'abc'
numbers_set_var = {6, 7}

# addition of string items to the set

print('numbers_set =', numbers_set_var)

info_dictionary_var = {'key': 1, 'lock' : 2}
numbers_set_var = {'a', 'b'}

# add keys of dictionary to the set
print('numbers_set_var =', numbers_set_var)r = 'abc'<br>numbers_set_var = {6, 7}

If the update() method is called with dictionaries, the dictionaries’ keys are added to the set.

Example 3: Working with a Python set update list.

# Python program to demonstrate the
# use of update() method

list1_var = [6, 7, 8]
list2_var = [10, 11, 12]
list3_var = [15, 16, 17]

# Lists converted to sets
set1_var = set(list2)
set2_var = set(list1)

# Update method

# Print the updated set

# List is passed as an parameter which
# gets automatically converted to a set

Example 4: Add dictionary items to set

number_var = {6, 7, 8, 9, 10}

num_Dict_var = {6: 'Six', 7: 'Seven', 8: 'Eight',9: 'Nine', 10: 'Ten'}


print("Updated set: ", number_var)

Example 5: Python set update() method example

In the following example, we have two sets of integers, X and Y, and we’re executing X.update(Y) to add the components of Set Y to Set X.

# Set X
X_var = {6, 7, 8}

# Set Y
Y_var = {7, 8, 9}

# Displaying X & Y before update()
print("X is:",X_var)
print("Y is:",Y_var)

# Calling update() method

# Displaying X & Y after update()
print("X variable is:",X_var)
print("Y variable is:",Y_var)

Example 6: Set update() method example with List, Tuple, String, Dictionary

Using the update() method, we add elements from a list, tuple, string, and dictionary to the calling set X in the following example.

# Set X
X_var = {6, 7, 8}

# List lis
lis_var = [8, 10]

# tuple
t_var = (82, 104)

# String
s_var = "abc"

# Dictionary dict
dict_var = {"one": 1, "two": 2}

# Calling update() method
X_var.update(lis_var, t_var, s_var, dict_var)

# Displaying X after update()
print("X variable is:",X_var)

Example 7: Insert the items from set y into set x

var_x = {"HP", "DELL", "IBM"}
var_y = {"google", "microsoft", "apple"}



From Multiple sets, update a set

Multiple iterables can be passed as parameters to the set.update() method.

var_nums = { 6, 7, 8 }
var_evenNums = { 7, 9, 11 }
var_primeNums = { 10, 12 }

nums.update(var_evenNums, var_primeNums)

print("Updated set: ", var_nums)

The | operator is used to update a set

Instead of using the update() function, the | symbol is used to update a set from another set, as seen below.

var_nums = { 6, 7, 8 }
var_evenNums = { 7, 9, 11 }
var_primeNums = { 10, 12 }

var_nums = var_nums | var_evenNums | var_primeNums
print("Updated set: ", var_nums)

Update a set from List, Tuple

As demonstrated below, the set.update() method also works with other iterables such as list, tuple, and dictionary. The | operator only works with updating sets from other sets; it does not work with other forms of iterables.

var_nums = {6, 7, 8}
var_oddNums = [6, 8, 10, 12, 14]
var_evenNums = (7, 9, 11, 13, 15)

var_nums.update(oddNums) # adding list elements
print("Updated set: ", var_nums)

var_nums.update(var_evenNums) # adding tuple elements
print("Updated set: ", var_nums)

# var_nums = var_nums | var_evenNums # throws error

Updating a dictionary set

When you offer a dictionary as a parameter, the set is updated using the dictionary’s keys.

var_nums = {6,7,8,9,10}
var_numsDict = {6:'Six',7:'Seven',8:'Eight',9:'Nine',10:'Ten'}
print("Updated set: ", var_nums)

What is the set update time complexity in Python?

The union operator’s runtime complexity is the same as the set.update() method’s runtime complexity. Because you must insert all m elements into the original set, if your set argument has m elements, the complexity is O(m). It is demonstrated in the following basic experiment, in which the set method is used numerous times to increase set sizes:

import matplotlib.pyplot as plt
import time

var_sizes = [i * 10**5 for i in range(50)]
var_runtimes = []

for size in sizes:
    var_s = set(range(1, size, 2))
    var_t = set(range(0, size, 2))

    # Start track time ...
    var_t1 = time.time()
    var_t2 = time.time()
    # ... end track time

plt.plot(var_sizes, var_runtimes)
plt.ylabel('Runtime (var_s)')
plt.xlabel('Set Size')


Python set update list

Set.update(list) is used to update an existing set with all elements from a provided list. It will populate the set with all elements from the list. All duplicate entries are deleted because the set data structure is duplication-free. Here’s an example of how a list can be passed as an argument. Python will simply run through the list, adding each entry to the existing set:

string_var = {6, 7, 8}
string_var.update(['student1', 'student1'])


Set update() takes another iterable as an argument, such as Set, List, String, or Dictionary, and adds the items of that iterable to the caller set. Only one appearance of an item will be present in the revised set if it appears in both sets.

You may also like

Leave a Comment