set()

Creates a set: an unordered collection of unique items.

Returns
A new set.
On this page

Example

#
Python
tags = ["html", "css", "html", "js", "css"]
unique = set(tags)

print(len(unique))
print(sorted(unique))
print("js" in unique)
print(type({}), type(set()))
Resultsaved result, you can check it
3
['css', 'html', 'js']
True
<class 'dict'> <class 'set'>

Definition and usage

#

The set() function creates a set. From a list or another iterable it keeps only the unique items, making it the simplest way to remove duplicates.

Sets don't keep order and have no indexes. In exchange, checking whether an item belongs to a set (x in my_set) is very fast, even with millions of items.

An empty set can only be created with set(), because {} means an empty dictionary. Sets support mathematical operations: union, intersection, and difference.

Syntax

#
Syntax
set()
set(iterable)

Parameters

#
  • iterable

    optional

    The items the set is built from.

Good practices

#
  • The result of set() has no fixed order. To display it, sort it with sorted().
  • If you check in often on a large list, convert it to a set.

Related entries

#

Spotted a mistake or missing an example? Write to us.