This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

# Data Structure - Sets¶

Another data type in Python is sets. It is a type that could store an unordered collection with no duplicate elements. It is also support the mathematical operations like union, intersection, difference, and symmetric difference. It is defined by using a pair of braces { }, and its elements are separated by commas.

{3, 3, 2, 3, 1, 4, 5, 6, 4, 2}

{1, 2, 3, 4, 5, 6}


One quick usage of this is to find out the unique elements in a string, list, or tuple.

TRY IT! Find the unique elements in list [1, 2, 2, 3, 2, 1, 2].

set_1 = set([1, 2, 2, 3, 2, 1, 2])
set_1

{1, 2, 3}


TRY IT! Find the unique elements in tuple (2, 4, 6, 5,2).

set_2 = set((2, 4, 6, 5, 2))
set_2

{2, 4, 5, 6}


TRY IT! Find the unique character in string “Banana”.

set('Banana')

{'B', 'a', 'n'}


We mentioned that sets support the mathematical operations like union, intersection, difference, and symmetric difference.

TRY IT! Get the union of set_1 and set_2.

print(set_1)
print(set_2)

{1, 2, 3}
{2, 4, 5, 6}

set_1.union(set_2)

{1, 2, 3, 4, 5, 6}


TRY IT! Get the intersection of set_1 and set_2.

set_1.intersection(set_2)

{2}


TRY IT! Is set_1 a subset of {1, 2, 3, 3, 4, 5}?

set_1.issubset({1, 2, 3, 3, 4, 5})

True