Append Multiple elements in set in Python

Pycharm Visual Studio Code

In Python, you cannot append elements to a set because sets are immutable. However, you can use the add method to add a single element to a set. If you want to add multiple elements to a set, you can use the update method or the union (|) operator to combine sets.

# Creating an empty set
my_set = set()

# Adding a single element
my_set.add(1)

# Adding multiple elements using update method
my_set.update([2, 3, 4])

# Adding multiple elements using union operator
my_set |= {5, 6, 7}

print(my_set)

Output:

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

An empty set my_set is created using set().

The add method is used to add a single element (1) to the set.

The update method is used to add multiple elements (2, 3, 4) to the set. You can pass an iterable (like a list) as an argument to update.

The union operator (|) is used to combine the set with another set containing elements 5, 6, and 7.

Now, my_set contains all the elements [1, 2, 3, 4, 5, 6, 7].

Remember that sets do not maintain order, so the elements may not be in the same order as they were added. Additionally, duplicate elements are automatically removed from sets.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • Python 3.8