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.
Code
Output
Loading...

Sets

.add()
Adds a specified single element to a set.
.clear()
Removes all elements from a set.
.copy()
Returns a shallow copy of a specified set.
.difference()
Returns a new set of objects unique to a given set when compared to others.
.difference_update()
Modifies a set by removing all elements present in another set.
.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.
.issuperset()
Checks whether all elements of the specified set exist in the original set.
.pop()
Removes and returns a randomly chosen element from a set.
.remove()
Removes the specified element from a set.
.symmetric_difference()
Returns elements that occur in either of the two sets but not in both.
.symmetric_difference_update()
Updates the original set by removing items present in both sets and adding items unique to each set.
.union()
Returns a new set that combines objects from all sets involved, removing any duplicates.
.update()
Updates the original set by adding elements from another set.
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