#5 - Python Sets

#5 - Python Sets

By Ifeanyi Omeata


Topics:


1. Sets


1. Sets


>>Return to Menu
Set is one of Python's four built-in data types for storing collections of data; the other three are List, Tuple, and Dictionary, all of which have different properties and applications.
A set is a collection of items that is unordered, unchangeable, and unindexed.
Curly brackets are used to write sets.
Note: A Set is not a Dictionary!

- Unordered:
Items do not have a defined order, and that order will continually change every time you use them, and cannot be referred to by index or key. If you add new items to a set, the new items may not be placed at the end of the set.

- Unchangeable:
We cannot change items in a set after it has been created. However, you can remove items and add new items.

- Do not allow Duplicates:
Sets are unindexed, hence they cannot have two items with the same value or repeated items.

#empty Set
#empty_set = {} # this is wrong, this is a dictionary
empty_set = set()

friends_set = {'John','Michael','Terry','Eric','Graham'}
people_set = {'Eric','Reg','Loretta','Colin','Graham'}

#print a set
print(friends_set)
#Items that are found in both sets
print(friends_set.intersection(people_set))
print(friends_set & people_set)
#Items that are found in first but not second set
print(friends_set.difference(people_set))
print(friends_set - people_set)
#Items that are only found in one set
print(friends_set.symmetric_difference(people_set))
print(friends_set ^ people_set)
#Join two sets together
print(friends_set.union(people_set))
print(friends_set | people_set)

image.png

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022