Python Set pop() Method

Python3 列表Python Sets


Description

The pop() method is used to remove and return a random element from the set. If the set is empty, it raises a KeyError exception.

Syntax

The syntax of the pop() method is:

set.pop()

Parameters

  • None

Return Value

Returns the removed element.

Example

Randomly remove an element:

Example 1

fruits = {"apple", "banana", "cherry"} fruits.pop() print(fruits)

The output result is:

{'apple', 'banana'}

Output return value:

Example 1

fruits = {"apple", "banana", "cherry"} x = fruits.pop() print(x)

The output result is:

banana

Notes

  • The elements in a set are unordered, so every time thepop()method is called, the removed element is random.
  • If you need to remove a specific element, you should use theremove()ordiscard()method, not thepop()。

Python3 列表Python Sets

Other Extensions