Open In App

set() Constructor in Python

Last Updated : 10 Nov, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

In Python, the set() constructor is used to create a set object. A set is a built-in data type that stores an unordered collection of unique elements. The set() constructor can be used to create an empty set or convert other data types (like lists, tuples, or strings) into a set.

Example:


Output
set() <class 'set'>
{1, 2, 3} <class 'set'>
{'o', 'l', 'h', 'e'} <class 'set'>

Syntax of set()

set([iterable])
  • iterable: This is an optional argument. If provided, it should be an iterable object (like a list, tuple, or string). The set() function will convert this iterable into a set.
  • If no iterable is passed, set() will create an empty set.

Use of set() Constructor

The set() constructor is commonly used for:

  • Creating an empty set.
  • Converting other data types (like lists, tuples, or strings) into sets.
  • Storing unique elements (duplicates are automatically removed).

Let’s explore a few examples to understand how this works in practice.

Convert a List to a Set

If you have a list with some duplicate values, you can convert it into a set to remove duplicates:


Output
{1, 2, 3, 4, 5}

Convert a String to a Set

When you convert a string to a set, each character in the string becomes an individual element of the set:


Output
{'n', 'a', 'b'}

Next Article
Article Tags :
Practice Tags :

Similar Reads