What is a set in Python?

A set is an unordered collection of unique items written inside curly braces { }. It has no index, and if you add a duplicate value, Python simply ignores it.

nums = {1, 2, 2, 3, 3}
print(nums)

a = {1, 2, 3}
b = {3, 4}
print(a | b)   # union
print(a & b)   # common items

Output:

Tutorials Class - Output Window

{1, 2, 3}
{1, 2, 3, 4}
{3}

Sets are useful to remove duplicates from data and to check membership quickly. To create an empty set use set(), because {} makes an empty dictionary. More in the Python Sets chapter.


Learn more about the similar topics:
Tutorials
Python Lists
Python Tuples
Python Sets
Python Dictionary
Exercises & Assignments
Python program to find largest and smallest number in a list
Python program to remove duplicates from a list
Interview Questions & Answers
What is a list in Python?
What is a tuple in Python?
What is a set in Python?
What is a dictionary in Python?
What is a negative index in Python and why is it used?
What is the difference between a list and a tuple in Python?
What are mutable and immutable types in Python?