Python .clear()

Anonymous contributor's avatar
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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours