Charming the Python: Sets

vickilanger profile image Vicki (she/her) Updated on ・1 min read

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.


Making a set

Python uses curly brackets for sets. Sets are unordered and have no index

dog_parts = {'paws', 'legs', 'tail', 'fur'}

Changing a Set

We cannot change items in a set, but we can add, update, and remove them.

dog_parts = {'paws', 'eyes', 'tail', 'fur'}

>>> paws, etes, tail, fur, whiskers

dog_parts.update('whiskers', 'nose', 'tongue')
>>> paws, eyes, tail, fur, whiskers, nose, tongue

Comparting Sets

Intersection shows the items shared between sets

dog_parts = {'paws', 'eyes', 'tail', 'fur'}
fish_parts = {'fins', 'gills', 'eyes', 'scales'}
>>> eyes

similarly, we can find which items are not shared

dog_parts = {'paws', 'eyes', 'tail', 'fur'}
fish_parts = {'fins', 'gills', 'eyes', 'scales'}
>>> paws, tail, fur, find, gills, scales

Series based on

Posted on by:

vickilanger profile

Vicki (she/her)


Vicki was once a manager of aircraft maintenance and is now charming Python. She coded #VetsWhoCode bot & Code Questions bot. When Vicki isn't petting her cat, she’s throwing a ball for her dogs.


markdown guide

I didn't even realize there were intersection and difference methods on sets. I've always used +, -, &, , | operators. The methods you listes are likely more intuitive and easier to read for more folks than the typical operators.