DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is Set in Python?

A Set in Python is a collection of unique elements. It does not allow duplicate values, and it is unordered.

We create a set using curly braces {} or the set() function.

  1. Example of Set:

numbers = {10, 20, 30, 40, 10}
print(numbers)

Output:
{10, 20, 30, 40}

Here, 10 appears only once because sets do not allow duplicate values:

  1. Important Characteristics of Set
  2. Does not allow duplicate values.
  3. Unordered collection.
  4. Mutable (we can add or remove elements).
  5. Does not support indexing.
  6. Can store different data types.

  7. Set Methods:

numbers = {10, 20, 30}
numbers.add(40)
numbers.remove(20)
numbers.discard(50)
print(numbers)

Output:
{10, 30, 40}

Top comments (0)