Skip to content

Set

A collection of unique items, unordered and unindexed.

Create

Create a set

Action Code Details
Empty set
set()
{} defines a dictionary!
Define with values
{'apple', 'banana', 'pear'}
From tuple
set(x)
From list
set(x)
From iterable (consumes)
set(x)
Union from a collection of sets
set().union(*x)

Test

Action Code Details
Is set or subclass
isinstance(x, set)
Is set and not subclass
type(x) is set
Empty
not x
Not empty
x
Contains value v
v in x
Contains None
None in x
Contains all of the given values
{v1, v2}.issubset(x)
Contains all of the given values
x.issuperset([v1, v2])
Contains any of the given values
not x.isdisjoint([v1, v2])
Contains none of the given values
x.isdisjoint([v1, v2])

Compare with another set

Action Code Details
Sets share no values
x.isdisjoint(y)
Set is a subset of the other: all values of x are in y
x.issubset(y)
Set is a superset of the other: all values of y are in x
x.issuperset(y)

Extract

Action Code Details
Number of (unique) values
len(x)
Hash
hash(frozenset(x))

Update

Grow

Action Code Details
Add value if needed
x.add('strawberry')
Add multiple values if needed
x.update(['strawberry', 'kiwi'])

Shrink

Action Code Details
Remove all values (clear)
x.clear()
Remove value
x.remove('strawberry')
Throws error if value is missing
Remove value if needed
x.discard('strawberry')

Derive

Combine

Combine with another set

Action Code Details
Union with another set
x | y
Union with another set
x.union(y)
Intersection with another set: get values which are present in both sets
x & y
Intersection with another set: get values which are present in both sets
x.intersect(y)
Difference to another set: get values which are not present in the other set
x - y
Difference to another set: get values which are not present in the other set
x.difference(y)
Symmetric difference with another set: get values that are not present in both sets
x ^ y
Symmetric difference with another set: get values that are not present in both sets
x.symmetric_difference(y)

Convert

The order of the values in the output should not be relied on

Action Code Details
Tuple of values
tuple(x)
List of values
list(x)