set() Built-in Function


Python set()

Python set() built-in function is used to create a new set. A set is a collection of unique items.

In this tutorial, you will learn the syntax of set() function, and then its usage with the help of example programs.

Syntax

The syntax of set() function is

set(iterable)

where

ParameterDescription
iterable[Optional Parameter] Takes elements from this iterable and keeps them in the set. Any duplicate elements shall be ignored, since a set can store only unique elements.

Examples

1. Create a set with elements from a list

In this example, we take a list of numbers, and create a set with the elements of this list, using set() function.

Python Program

myList = [2, 4, 8, 4, 6, 2]
mySet = set(myList)
print(mySet)

Output

{8, 2, 4, 6}

2. Create empty set

Iterable parameter is optional to set() function. If we do not pass any iterable as argument to set() function, then it returns an empty set.

In this example, we create an empty set using set() function.

Python Program

mySet = set()
print(mySet)

Output

set()

3. Add elements to set

We may add elements to the set using set.add() method.

Python Program

mySet = set()
mySet.add(2)
mySet.add(4)
print(mySet)

Output

{2, 4}

Summary

In this Python Built-in Functions tutorial, we learned the syntax of set() builtin function and how to use it, with the help of examples.