Python Practice › Set Programs › Program 24

Remove an arbitrary element

EasySet Programs · 24 of 48

Write a Python program to remove and return an arbitrary element with pop().

Advertisement
Input
{10, 20, 30}
Output
True 2

Approach

  1. pop() removes some element; you cannot choose which.

Solution

Python
s = {10, 20, 30}item = s.pop()print(item in {10, 20, 30}, len(s))
Output
True 2

Line by line

Line 2

Which element comes out is an implementation detail, so the program checks the result instead of printing a value that could differ.

Tip

For a truly random choice, use random.choice(list(s)).

Learn the concept

New to this topic? Read the lesson, then come back.

More set programs

← All 48 Set Programs

Leave a Comment