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'}
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
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
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
Series based on
Top comments (1)
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.