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

.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

Looking to contribute?

Learn Python on Codecademy