Set
Introduction
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.
Learn more about sets in these materials:
Assignment
Todo
What's Next
Todo