Learning Python: Sets

Sets are another important data structure in Python. They differ from dictionaries in that they do not have keys and they differ from tuples in that they are both mutable and unordered.

Examples

A simple set:

employee_name = {"Peter", "Johnson"}

Intersecting between two sets:

set1 = {"Peter", "Johnson"}
set2 = {"James"}

result = set1 | set2 # {'Johnson', 'James', 'Peter',}

We can also get the difference between two sets:

set1 = {"Peter", "Johnson"}
set2 = {"James"}

result = set1 - set2 # {'Peter', 'Johnson'}

A set can be checked if it is a superset of another set:

set1 = {"Peter", "Johnson"}
set2 = {"James"}

superset = set1 > set2 # False

We can get the length of a set using the len() method:

employee_name = {"Peter", "Johnson"}
len(set1) # 2

We can create a list by passing the set:

employee_name = {"Peter", "Johnson"}
list(employee_name)

We can check if an element is contained in a set using in:

print("Peter" in employee_name) # True

This blog post was originally published on my blog Communicode, where I write about different tech topics.

Python
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.