Append Values to a Set in Python

  1. Append a Single Value to a Set With the add() Method in Python
  2. Append Multiple Values to a Set With the update() Method in Python
  3. Append a Set to Another Set With the |= Operator in Python

In this tutorial, we will discuss methods to append values to a set in Python.

Append a Single Value to a Set With the add() Method in Python

The add() method can add a single value to the set in Python. The following code example shows us how we can append a single value to a set with the add() function in Python.

a = {1, 2, 3}

a.add(4)

print(a)

Output:

{1, 2, 3, 4}

In the above code, we first initialize a set a and then append the value 4 to the end of the set a with the add() function.

Append Multiple Values to a Set With the update() Method in Python

The update() method can be used to append multiple values to a set. The update() method is designed to append data-structures like lists and arrays to the set. So, it only takes one argument. But, we can pass in as many arguments as we want by just enclosing all the arguments into a single (). The following code example shows us how we can append multiple values to a set with the update() function in Python.

a = {1, 2, 3}

a.update((4, 5, 6))

print(a)

Output:

{1, 2, 3, 4, 5, 6}

In the above code, we first initialize a set a and then append the values 4, 5, 6 to the end of the set a with the update() function.

Append a Set to Another Set With the |= Operator in Python

The | operator, also known as the concatenation operator, concatenates the variables on each side of the operator. The |= operator appends the set on the operator’s right side to the set on the operator’s left side. The following code example shows us how we can append a set to another set with the |= operator in Python.

a = {1, 2, 3}
b = {4, 5, 6}

a |= b

print(a)

Output:

{1, 2, 3, 4, 5, 6}

In the above code, we first initialize sets a and b and then append the set b to the end of the set a with the |= operator.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Set

  • Check if Set Is Empty in Python
  • Join Two Sets in Python