Charming the Python: Sets

vickilanger

Vicki Langer

Posted on December 7, 2019

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

💖 💪 🙅 🚩
vickilanger
Vicki Langer

Posted on December 7, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related