.clear()
Anonymous contributor
Published Jun 28, 2024
Contribute to Docs
In Python, the .clear()
method removes all elements from a set, resulting in an empty set. This method does not return any value.
Note: The
.clear()
method performs the operation in-place, modifying the original set rather than creating a new one.
Syntax
set_object.clear()
set_object
: The set from which all elements will be removed.
Example
In the example below, the .clear()
method is used to remove all elements from the pets
set, leaving it empty:
pets = {"cats", "dogs", "hamsters", "lizards", "turtles"}print("Original set:", pets)pets.clear()print("After calling clear() on pets:", pets)
The resulting output will look like this:
Original set: {'hamsters', 'dogs', 'turtles', 'cats', 'lizards'}After calling clear() on pets: set()
Note: A set in Python is unordered. That’s why the order of items in
Original set
may appear different in the above output.
Codebyte Example
Run the following code to see how the .clear()
method works:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours