If we need to remove an element from a set, we can use .remove().

This method can remove a single item from a set with the following syntax:


Let’s revisit the set plantShelf from the previous exercise:

var plantShelf: Set = ["Haworthia", "Graptopetalum", "Echeveria", "Corpuscularia"]

Unfortunately, we overwatered the "Haworthia" plant, and it wilted away.

To remove this value from plantShelf using .remove(), we can use this code:


If we tried to remove a value that didn’t exist within the set plantShelf, like "Astridia", the set would be unaffected.

If we wanted to remove every single element from a set, we could use the .removeAll() method:


Let’s say we are moving our plant collection over to the window sill. Removing all the values from plantShelf looks like this:


If we print the value of plantShelf after removing all the values, the output looks like this:




Take a look at the set in Planets.swift. Since "Pluto" is no longer considered a planet, we should remove it from our set.

Remove the value "Pluto" from the set planets using .remove().

Print the value of planets.


We have entered the Andromeda Galaxy!

Remove all the values from planets using .removeAll().

Print the value of planets again.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?