VOOZH about

URL: https://www.geeksforgeeks.org/python/python-set-function/

⇱ set() Function in python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

set() Function in python

Last Updated : 17 Feb, 2026

set() function in Python is used to create a set, which is an unordered collection of unique elements. It removes duplicate values automatically and accepts an iterable such as a list, tuple, string, range or dictionary.

Example: In this example, set() is used to create a set from a list containing duplicate values.


Output
{1, 2, 3}

Explanation: set(a) converts the list a into a set and duplicate value 2 is removed automatically.

Syntax

set(iterable)

  • Parameters: iterable (optional) - An iterable like list, tuple, string, range or dictionary. If not provided, it creates an empty set.
  • Returns: Returns a new set with unique elements.

Examples

Example 1: In this example, an empty set is created using set(). This is useful when elements need to be added later.


Output
set()
<class 'set'>

Explanation: set() creates an empty set and type(s) confirms the object is a set.

Example 2: In this example, a list with duplicate values is converted into a set. This removes all repeated elements.


Output
{4, 5, 6, 7}

Explanation: set(a) removes duplicate value 5 and only unique elements remain.

Example 3: In this example, a tuple is converted into a set. Duplicate values are removed automatically.


Output
{1, 2, 3}

Explanation: set(t) converts tuple t into a set, duplicate value 1 is removed.

Example 4: In this example, range() is used with set() to create a set of numbers.


Output
{3, 4, 5, 6, 7}

Explanation: set(range(3, 8)) creates a set from numbers generated by range().

Example 5: In this example, a dictionary is passed to set(). Only dictionary keys are included in the set.


Output
{'x', 'z', 'y'}

Explanation: set(d) takes only the keys from dictionary d, values are not included.

Related Articles:

Comment