Site icon Meccanismo Complesso

Python Lessons – 6.7 Sets

Python Lesson - 6.7 Sets m
Python lessons - 6.7 Sets


Sets are data structures similar to lists or dictionaries. These are created using the brackets {} or directly the set() function. This data structure shares some functionalities with lists, for example the use of the in clause to know if a particular value is contained within.

set1 = {1,4,6,3}
set2 = set(["One","Two","Three"])
print(3 in set1)
print("One" in set2) 

if you run it, you get:


Sets differ from the lists in many respects, for example they are not ordered and therefore there are no indexes that refer to them inside. Furthermore they can not contain duplicate values. As far as performance is concerned, the survey if a value is contained within a set is more efficient than that for a list.

To add an element to a set you have to use the add () method (in the lists you can use append ()), to remove it you have to use remove () and the method pop () returns the first one that was inserted by deleting it from the set.

set1 = set()

if you run it, you get

{1, 4, 6}
{4, 6}

Operators on sets

Sets can be used to perform some mathematical operations typical of sets.

Let’s see an example

A = {1,4,6,3}
B = {4,5,9,2}
print(A | B)
print(A & B)
print(A - B)
print(A ^ B) 

if you run it, you get

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

⇐ Go to Python Lesson 6.6 – Recursions

Go to Python Lesson 6.8 – The itertools module ⇒

Exit mobile version