Sets

BrandonDusch580 total contributions
Published Aug 31, 2021Updated May 23, 2022
Contribute to Docs
A set is an unordered collection of elements without any duplicates.
Sets are especially useful for performing logical operations like finding the union, intersection, or difference between collections of elements. For example, sets could be used to determine mutual friends on a social networking site.
Syntax
set_A = set(iterable)
set_B = {element_A, element_B, ..., elementZ}
There are several ways to create a set, which include:
- Using the built-in
set()
function and passing in an optionaliterable
parameter. - Hard-coding a set with dictionary-like syntax (
{}
) where each element is unique.
Codebyte Example
In the example below, sets are created with lists and the set()
function. The following observations can be made:
- The first time the
animals
set is created with no parameters and printed, “set()” is printed to the shell. - When the
dog_breeds
set is created, it has duplicate elements with acorgi
value that is reduced to one by the time the set is printed.
Sets
- .difference()
- Returns a new set of objects unique to a given set when compared to others.
- .intersection()
- Returns a new set with objects that exist inside two or more sets
- .union()
- Returns a new set that combines objects from all sets involved, removing any duplicates.
All contributors
- BrandonDusch580 total contributions
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- AndrewBarbour4 total contributions
- BrandonDusch
- christian.dinh
- Anonymous contributor
- AndrewBarbour
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.