Set
A set in Python is unordered collection of unique elements. Unordered means it does not keep the order of the elements and unique means it does not allow duplicates.
Its mostly used when removing duplicates from list or performing quick membership tests (checking to see if some element belongs to both sets).
Lesson Overview
In this lesson we will cover:
- How to create set
- How to access elements of the set
- Adding or removing elements
- Set operations
Creating Set
Creating sets in Python is done with curly braces {} or its constructor set().
To create an empty set, we need to use set() function as using {} will create a new dictionary (which we will cover in the next lesson).
Accessing Elements
We cannot access elements of the set like we did with other data structures using index, but we can iterate over it with for loop or check if the item exists with in keyword :
Adding and Removing Elements
We can use .add() method to add a single element to set or use .update() method to add multiple elements.
Removing the elements can be done with .remove() method which raises KeyError if that element does not exist.
Set Operations
Sets support mathematical operations like union, intersection, and difference, making them useful for comparing collections.
Explore Python sets deeper by visiting this [built-in: set] article from Real Python (especially the part about additional methods which come in handy when working with sets).
Remember you do not need to remember all the methods there are. Just read through them, to know they exist.
Exercise
Complete [TODO] Exercise 07 — WorkingTitle to practice sets.
Assignment
In this assigment our task is simple one. We need to track distinct unsold items so we can better prepare for the next day in our little shop.
- Open
main.pyfile we have been working on. - Define a set for all sold items (
item[0]of element inorderlist) and define a set of all inventory items (item[0]of element ininventorylist) - you can use set coprehension to do this in one line or use a for loop to iterate over each item in the lists. - Create a variable
unsold_itemsand set its value to besold_itemssubstracted fromall_inventory_items - Print out items that did not have a sale today.
- Confirm the program works, commit and push to Github
What's Next
Now that we covered index based data structures, it's time to meet dictionary which is unique in its key-value approach and is probably most used data structure (besides lists).