Python .pop()

Anonymous contributor's avatar
Anonymous contributor
Published Jun 29, 2024
Contribute to Docs

In Python, the .pop() method randomly removes an element from a set and returns the element that was removed. If the set is empty, the method will raise a TypeError since there are no elements to remove from the set.

  • 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.pop()
  • set: The set from which an element will be removed.

Example

The following example demonstrates the usage of the .pop() method:

set1 = {"Alpha", "Beta", "Gamma"}
print(set1.pop())
print(set1)

The output of .pop() will vary each time it is executed since the method removes and returns a random element from the set. Here is one potential output of this example where Beta is randomly selected to be removed from set1:

Beta
{'Gamma', 'Alpha'}

Codebyte Example

Here is a codebyte example to understand how the .pop() method works:

Code
Output

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