Sets

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 optional iterable 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 a corgi value that is reduced to one by the time the set is printed.
us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

Sets

.difference()
Returns a new set of objects unique to a given set when compared to others.
.discard()
Removes a specified element from a set.
.intersection()
Returns a new set with objects that exist inside two or more sets
.isdisjoint()
Checks whether two sets contain a common element in them.
.issubset()
Checks whether all elements in one set exist within another specified set.
.remove()
Removes the specified element from a set.
.union()
Returns a new set that combines objects from all sets involved, removing any duplicates.
frozenset()
Returns a new set or frozenset object whose elements are picked from a given iterable.

All contributors

Looking to contribute?

Learn Python on Codecademy