DEV Community

Vicki Langer
Vicki Langer

Posted on • Updated on

Charming the Python: Sets

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


Sets

Making a set

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

dog_parts = {'paws', 'legs', 'tail', 'fur'}
Enter fullscreen mode Exit fullscreen mode

Changing a Set

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

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

dog_parts.add('whiskers')
print(dog_parts)
>>> paws, etes, tail, fur, whiskers

dog_parts.update('whiskers', 'nose', 'tongue')
print(dog_parts)
>>> paws, eyes, tail, fur, whiskers, nose, tongue
Enter fullscreen mode Exit fullscreen mode

Comparting Sets

Intersection shows the items shared between sets

dog_parts = {'paws', 'eyes', 'tail', 'fur'}
fish_parts = {'fins', 'gills', 'eyes', 'scales'}
print(dog_parts.intersection(fish_parts))
>>> eyes
Enter fullscreen mode Exit fullscreen mode

similarly, we can find which items are not shared

dog_parts = {'paws', 'eyes', 'tail', 'fur'}
fish_parts = {'fins', 'gills', 'eyes', 'scales'}
print(dog_parts.difference(fish_parts))
>>> paws, tail, fur, find, gills, scales
Enter fullscreen mode Exit fullscreen mode

Series based on

Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker • Edited

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.