Set Characteristics
Unique
A set is a collection of unique items that belong together for some reason.
Example:
- A set of prime numbers up to a hundred
- A set of default type faces on Windows 95
- A set of of your favorite foods
Compared
Sets can also be compared.
So for example comparing a set of my favorite foods and your favorite foods would make a new set of the foods that we both love.
No Indexes
Python sets are iterable collections like list and tuples, but each item is unique and the set doesn’t have any indexes.
Python sorts the sets in a way that makes sense to Python. It may look like it’s doing them a natural order but you will see times where it doesn’t look like a natural order for how your sets are sorted.
Set Creation
Creating Sets with { }
>>> {1, 3, 5} {1, 3, 5}
Creating Empty Sets with set( )
>>> var1 = {} # This way you create an empty dictionary >>> type(var1) <class 'dict'>
>>> var2 = set({}) # This is how you create an empty set
>>> type(var2)
<class 'set'>
Eliminate repetition inside an iterable with set( )
One of the most common ways you’ll see sets being used is to make some other iterable unique.
my_list = list(set(my_list))
Set Updating
Adding to Sets with add( ) and update( )
>>> low_primes = {1,3,5,7,11,13} >>> low_primes.add(17) {1,3,5,7,11,13,17}
>>> low_primes.update({19,23}, {2,29}) >>> low_primes {1,2,3,5,7,11,13,17,19,23,29}
Items Removal
Removing Set Items with remove( )
>>> low_primes.add(15) {1,2,3,5,7,11,13,15,17,19,23,29} >>> low_primes.remove(15) {1,2,3,5,7,11,13,17,19,23,29}
But the remove() function throws an error if it doesn’t find the item you’re trying to delete.
>>> low_primes.remove(100) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 100
Removing Items without Errors with discard( )
The function discard() doesn’t throw an error if it doesn’t find the item to be removed. Simple as that.
>>> low_primes.discard(100) >>> low_primes {1,2,3,5,7,11,13,17,19,23,29}
Remove items with pop( )
while low_primes:
print(low_prime.pop())