Nik Nik - 1 year ago 73
Python Question

Python | Access the sole element of a set

I have a

in Python from which I am removing elements one by one based on a condition. When the set is left with just 1 element, I need to return that element. How do I access this element from the set?

A simplified example:

S = set(range(5))
for i in range(4):
S = S - {i}
# now S has only 1 element: 4
return ? # how should I access this element
# a lame way is the following
# for e in S:
# return S

Answer Source

Use set.pop:

>>> {1}.pop()

In your case, it would be:

return S.pop()

Note however that this will remove the item from the set. If this is undesirable, you can use min|max:

return min(S) # 'max' would also work here


>>> S = {1}
>>> min(S)
>>> S
>>> max(S)
>>> S
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download