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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |