Working with Sets in Python

Understanding how to create and manipulate Sets in Python.

Giulio Laurenti, PhD
Geek Culture

--

Photo by Cristina Anne Costello on Unsplash

Sets are one of the built-in data structures in Python. They are unordered sequences of unique elements that can contain different data types.

Unordered means that the elements of a set do not occupy a fixed position and we cannot access them using their index.

In this post, we will learn how to create and manipulate sets.

Creating sets
Sets are created by either including the elements between curly braces {}, similar to dictionaries, or by using the set() function, which takes iterables such as tuples or lists.

# Create a set called motorbikes using curly brackets.
motorbikes = {"Ducati", "Aprilia", "MV Augusta", "Yamaha"}

# Create the same set using the set() function and a list of bikes.
motorbikes = set(["Ducati", "Aprilia", "MV Augusta", "Yamaha"])

print(motorbikes)
{'Ducati', 'Yamaha', 'Aprilia', 'MV Augusta'}

Sets do not allow for duplicate elements. If we try to create a set with duplicates, only one of the entries will be retained.

# Create a set with duplicate values

motorbikes = {"Ducati", "Aprilia", "MV Augusta", "Aprilia", "Yamaha"}
print(motorbikes)
{'Yamaha', 'MV Augusta', 'Aprilia', 'Ducati'}

--

--

Giulio Laurenti, PhD
Geek Culture

A Molecular Biologist who enjoys writing about programming, science, and the wonderful world around us.