Published: Aug. 22, 2019 by lukemakin |  estimated reading time: 8 minutes
This is the 4th and final part of python data structure series which will cover sets and frozensets. Sets are unordered data collections, that take only unique values. The difference between sets and frozensets is that the first ones are mutable while the second are not. Let's take a look at the most interesting methods related to these data collections with examples, starting from defining the sets:

best_football_players = set(['Cristiano Ronaldo', 'Leo Messi', 'Luka Modric'])
best_football_players2 = {'Cristiano Ronaldo', 'Leo Messi', 'Luka Modric'}

print(type(best_football_players))
print(type(best_football_players2))

'''
Output:
<class 'set'>
<class 'set'>
'''

Above we defined sets with a set() constructor taking a list as a input, and traditional way with curly brackets (like in dictionaries). Both return the same type so from now on we will be workin with the 'best_football_players' variable. Let's add some players to our set from a list using a for loop:


players_to_add = ['Cristiano Ronaldo', 'Robert Lewandowski', 'Marco Reus']

for player in players_to_add:
best_football_players.add(player)

print(best_football_players)

'''
Output:
{'Cristiano Ronaldo', 'Robert Lewandowski', 'Leo Messi', 'Luka Modric', 'Marco Reus'}
'''

Notice that we passed 'Cristiano Ronaldo' as a player to be added, but since CR7 was already in the list - we didn't duplicate him (there could be only on Cristiano you can say). Let's now look at the ways to remove players form the set, starting with a player that doesn't exist in the 'best_football_players' set:


best_football_players.remove("Manuel Neuer")
print(best_football_players)

'''
Output:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-16-b6eae7cf9360> in <module>
----> 1 best_football_players.remove("Manuel Neuer")
2 print(best_football_players)

KeyError: 'Manuel Neuer'
'''

So when using the remove method we must be careful -  if the the item that we want to delete is not there - KeyError will appear. To prevent this from happening you can use discard() method:


best_football_players.discard("Manuel Neuer")
print(best_football_players)

'''
Output:
{'Cristiano Ronaldo', 'Robert Lewandowski', 'Leo Messi', 'Luka Modric', 'Marco Reus'}
'''

There is also the pop() method that removes an random item, but since sets are unordered,  you won't know what was removed:


best_football_players.pop()
print(best_football_players)

'''
Output:
{'Robert Lewandowski', 'Leo Messi', 'Luka Modric', 'Marco Reus'}
'''

Now let's add a all time best list and compare it with the current list starting with the difference method:


all_time_best = {'Ronaldo', 'Zinedine Zidane', 'Cristiano Ronaldo', 'Leo Messi', 'Pele', 'Maradonna'}

diff = all_time_best.difference(best_football_players)
print(diff)

'''
Output:
{'Cristiano Ronaldo', 'Pele', 'Ronaldo', 'Zinedine Zidane', 'Maradonna'}
'''

So the output is basically the collection of all elments appearing only in one of the sets. As next step let's look a opposite situation, where a method returns a name that is a common part for both of the collections:


inter = all_time_best.intersection(best_football_players)
print(inter)

'''
Output:
Leo Messi
'''

Let's now delete the sets using two methods and compare them:


best_football_players.clear()
del all_time_best

print(best_football_players)
print(all_time_best)

'''
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-88-139028bbb0a2> in <module>
1 best_football_players.clear()
----> 2 del all_time_best
3
4 print(best_football_players)
5 print(all_time_best)

NameError: name 'all_time_best' is not defined
'''

As you can see, the difference is that clear removes all the lements in the set, while delete removes the set from the memory. So in theory we should be able to add elements to our empty best players data collection. Let's try to do that using update method():


best_football_players.update(["Cristian Pulisic", 'Kylian Mbappe'])
print(best_football_players)

'''
Output:
{'Kylian Mbappe', 'Cristian Pulisic'}
'''

And check the size of our set:


print(len(best_football_players))

'''
Output:
2
'''

Finally lets take a look at frozensets, which basically are untouchable because they're unchangeable:


best_goalkeepers = ['Gianluigi Buffon', 'Manuel Neuer']
best_goalkeepers = frozenset(best_goalkeepers)

print(type(best_goalkeepers))

'''
Output:
<class 'frozenset'>
'''

To verify if they are in fact immutable:


print(best_goalkeepers.add("Wojciech Szczesny"))

'''
Output:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-93-4057937710cb> in <module>
----> 1 print(best_goalkeepers.add("Wojciech Szczesny"))

AttributeError: 'frozenset' object has no attribute 'add'
'''

And this is it for this part and the whole 4 part series. Be sure to checkout the previous articles related to data structures:

https://pyplane.com/blog/python-data-structures-part1-lists/

https://pyplane.com/blog/python-data-structures-part2-dictionaries/

https://pyplane.com/blog/python-data-structures-part3-tuples/

 
Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com