Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Set pop() Method

Python Set pop() Method

Python3 Lists Python Sets


Description

The pop() method removes and returns a random element from a set. If the set is empty, a KeyError exception is raised.

Syntax

Syntax of the pop() method:


set.pop()

Parameters

Return Value

Returns the removed element.

Example

Randomly remove an element:

Example 1

fruits

= {

"

apple

"

,

"

banana

"

,

"

cherry

"

}

fruits

.

pop

(

)

print

(

fruits

)

The output is:


{'apple', 'banana'}

Output the return value:

Example 1

fruits

= {

"

apple

"

,

"

banana

"

,

"

cherry

"

}

x

=

fruits

.

pop

(

)

print

(

x

)

The output is:


banana

Notes

Python3 Lists Python Sets