set() Builtin Function

Python set()

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

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

Create 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)
Run

Output

{8, 2, 4, 6}

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)
Run

Output

set()

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

Python Program

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

Output

{2, 4}

Summary

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