Python - How To Append Values to a Set in Python

ID : 485

viewed : 243

Tags : PythonPython Set

vote vote

93

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 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 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.

  • Related HOW TO?