PythonBuilt-in functions
set()
Creates a set: an unordered collection of unique items.
- Returns
- A new set.
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 withsorted(). - If you check
inoften on a large list, convert it to a set.
Related entries
#- set.add()Adds an element to a set. If the element is already there, the set doesn't change.
- set.union()Returns a new set with the elements from every given set, without duplicates.
- list()Creates a list, either empty or from the items of another iterable.
- sorted()Returns a new, sorted list built from the items of any collection.
Spotted a mistake or missing an example? Write to us.