The Python programming language is among the most popular in the world today. In this article, we are going to learn about sets in python and find out if sets are mutable or not. We will be discussing some examples based on this too.

What are Sets in Python?

A set is an unordered collection of data or items. It is basically a type of data or data type used to store multiple items in a single variable. It is a built-in data type. In order to create a set, you either need to place all the elements inside curly braces ( [ ] ) or you can use the built-in function set().

  1. An unordered set is a set of items.
  2. Unique elements make up a set. The use of duplicate elements is prohibited.
  3. In spite of the fact that a set can be modified, the elements it contains must be immutable.

Example:

set1 = {1, 2, 3, 4, 3, 1}
set2 = set(1, 2, 3, 1, 2)
print(set1)
print(set2)

The output of this piece of code will be:

{1, 2, 3, 4}
{1, 2, 3}

Are Python sets mutable?

Yes, Python sets are mutable, i.e., we can add or remove elements from it. On the other hand, items of a set in python are immutable. In Python, sets do not have duplicate elements and are unordered. Sets cannot be changed once they have been created. The elements of a set can be of any data type like: String, Boolean, tuple, float, int.

Note:

Hashing is not possible for mutable elements

Hashing is possible for immutable elements

Example 1: Adding a single element using the add() method.

set1 = {1, 3}
print(set1)
set1.add(2)
print(set1)

The output of this piece of code will be:

{1, 3}
{1, 2, 3}

Note: If the set was immutable then compiler would have shown TypeError.

Example 2: Using the update() method to add multiple elements to the set.

set2 = {1, 3}
print(set2)
set2.update([2, 3, 4])
print(set2)

The output of this piece of code will be:

{1, 3}
{1, 2, 3, 4}

Note: The update() method can take tuples, lists, strings or other sets as its argument.

So as seen above, sets in python are indeed mutable. But the elements inside the sets are immutable, which can increase the security and efficiency of our program.

Is this not the answer you’re looking for? Ask your own question about Python set or browse other questions tagged python set.

More interest articles related to Python are :

Final Project – Blackjack