Access the sole element of a set

0 votes

I have a set 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

Jun 28, 2019 in Python by ana1504.k
• 7,890 points

1 answer to this question.

0 votes

Use set.pop:

>>> {1}.pop()

In your case, it would be:

return S.pop()
answered Jun 28, 2019 by SDeb
• 13,250 points

Related Questions In Python

0 votes
1 answer

How do I run a set of code for all the requests in Flask?

Hi, You can use dedicated hooks(decorators) called before ...READ MORE

answered Jun 20, 2019 in Python by Shabnam
• 920 points
0 votes
1 answer

How to access the elements of a dictionary using index ?

Suppose you have a dictionary num = ...READ MORE

answered Jul 4, 2019 in Python by Arvind
• 2,980 points
0 votes
1 answer

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Hello @kartik, Since different users might have different ...READ MORE

answered Jun 15 in Python by Niroj
• 34,940 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,087 views
0 votes
0 answers
0 votes
1 answer

Return a list inside a for loop while iterating over the elements of another list

The print() is getting called multiple times ...READ MORE

answered Sep 21, 2018 in Python by SDeb
• 13,250 points
0 votes
1 answer

How to check the version of Python?

you can check the version of python ...READ MORE

answered Sep 25, 2018 in Python by SDeb
• 13,250 points