You are on page 1of 2

2021/5/13 4.5. Sets — Python Notes (0.14.

0)

Python Notes (0.14.0)


P R E VIOUS | N E X T | M O D ULES | I N D EX

4.5. Sets
SEARCH
Contents
Sets Go
Quick example Enter search terms
Ordering or a module, class or
Operators function name.

This page: Show


Sets are constructed from a sequence (or some other source.
iterable object). Since sets cannot have duplicated,
TABLE OF
there are usually used to build sequence of unique CONTENTS
items (e.g., set of identifiers).
1. Quick Start /
Tutorial
4.5.1. Quick example 2. Variables,
>>> a = set([1, 2, 3, 4]) expressions,
>>> b = set([3, 4, 5, 6]) statements,
>>> a | b # Union
types
{1, 2, 3, 4, 5, 6}
>>> a & b # Intersection 1. Iterators
{3, 4}
>>> a < b # Subset 2. Generators
False
>>> a - b # Difference 3. Exceptions
{1, 2}
>>> a ^ b # Symmetric Difference 4. Decorators
{1, 2, 5, 6}
5. Classes
Note
6. Namespace and
the intersection, subset, difference and symmetric
difference can be be called with method rather that scoping rules
symbols. See below for examples.
7. Packaging

8. Notes about
4.5.2. Ordering
sorting lists and
Just as with dictionaries, the ordering of set elements is dictionaries
quite arbitrary, and shouldn’t be relied on.
9. Notes about
booleans and
4.5.3. Operators logical operators

As mentionned in the quick example section, each 10. Notes on


operator is associated to a symbol (e.g., &) and a
method name (e.g. union).

>>> a = set([1, 2, 3])


>>> b = set([2, 3, 4])
>>> c = a.intersection(b) # equivalent to c = a &

https://thomas-cokelaer.info/tutorials/python/sets.html 1/2
2021/5/13 4.5. Sets — Python Notes (0.14.0)

>>> a.intersection(b)
set([2, 3])

>>> c.issubset(a)
True
>>> c <= a
True
SEARCH
>>> c.issuperset(a)
False
>>> c >= a Go
False Enter search terms
or a module, class or
>>> a.difference(b)
function name.
set([1])
>>> a - b This page: Show
set([1])
source.

>>> a.symmetric_difference(b) TABLE OF


set([1, 4]) CONTENTS
>>> a ^ b
1. Quick Start /
set([1, 4])
Tutorial
You can also copy a set using the copy method:
2. Variables,
>>> a.copy() expressions,
set([1, 2, 3])
statements,
types

1. Iterators

2. Generators

3. Exceptions

4. Decorators

5. Classes

6. Namespace and
scoping rules

7. Packaging

8. Notes about
sorting lists and
dictionaries

9. Notes about
booleans and
logical operators

10. Notes on

https://thomas-cokelaer.info/tutorials/python/sets.html 2/2

You might also like