From the course: Programming Foundations: Data Structures

Unlock the full course today

Join today to access over 24,700 courses taught by industry experts.

Mutate a set in Python

Mutate a set in Python

- [Instructor] Sets in Python are mutable, meaning we can modify them by adding, removing, or updating their elements. This flexibility makes sets ideal for situations where you need a collection of unique items that can change over time. Another way we can create a set is with the curly braces as shown here. To add a single element to a set, we can use the add method. This method takes one argument and adds it to the set if it's not already present. If we run this, we'll see that orange has been added to the set. Now, if orange was already in the set, Python would ignore it, since sets automatically discard duplicates. If you want to add several elements at once, you can use the update method. This takes in another Iterable, like a list or another set, and adds each element to the set. An Iterable in Python is any object that can be looped over, meaning it's capable of returning its elements one at a time. Let's see the updated fruits. Both mango and grape have been added to our set…

Contents