Python Set

Rumman Ansari   Software Engineer   2022-11-27   313 Share
☰ Table of Contents

Table of Content:


What is Set in python?

A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.


Python’s built-in set type has the following characteristics:

  • Sets are unordered.
  • Set elements are unique. Duplicate elements are not allowed.
  • A set itself may be modified, but the elements contained in the set must be of an immutable type.

Duplicates Not Allowed

Sets cannot have two items with the same value.

vegetableSet  = {"Tomato", "Potato", "Carrot", "Tomato"}

print(vegetableSet)

Output:

{'Potato', 'Tomato', 'Carrot'}

Get the Length of a Set

To determine how many items a set has, use the len()

vegetableSet  = {"Tomato", "Potato", "Carrot", "Ginger"}

print(len(vegetableSet))

Output:

4