An Introduction to Python Sets - Part I

Defining set objects in Python

Chaitanya Baweja
Python Pandemonium

--

You must have come across sets and set theory in your high school education. It’s the same class where you used to draw these cool overlapping circles called Venn diagrams.

A Venn Diagram (Source : realpython.com [link])

While a rigorous definition of a set can be abstract, a set can be simply defined as an unordered collection of items. Every element in a set is unique (no duplicates) and a variety of operations like union, intersection etc. can be performed on a set.

Grouping objects into a set can be useful in programming as well, and Python provides a built-in set type to do so. What you’ll learn in this tutorial:

  1. How to define set objects in Python
  2. Discover some of the operations supported natively.
  3. Set operations in detail and get a understanding as to when a set is an appropriate choice.

This tutorial has been divided into three parts for ease of access. Link to tutorial for part II and III will be added soon.

Defining a Set

There are two ways to define a set in Python:

  • built-in set() function
  • with curly braces {}

Using set function

--

--

Chaitanya Baweja
Python Pandemonium

Machine Learning Engineer | Python | Data Analytics | Economics | Physics