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,910 points
494 views

1 answer to this question.

0 votes

Use set.pop:

>>> {1}.pop()
1
>>>

In your case, it would be:

return S.pop()
answered Jun 28, 2019 by SDeb
• 13,300 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 21, 2019 in Python by Shabnam
• 930 points
587 views
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
• 3,040 points
2,006 views
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, 2020 in Python by Niroj
• 82,880 points
22,911 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,075 views
0 votes
1 answer
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 22, 2018 in Python by SDeb
• 13,300 points
4,683 views
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,300 points
622 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP