Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (19k points)

Suppose the following:

>>> s = set([1, 2, 3])

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.

Quick and dirty:

>>> elem = s.pop()

>>> s.add(elem)

But do you know of a better way? Ideally in constant time.

1 Answer

0 votes
by (106k points)

If you want to retrieve an element from a set without removing it the below-mentioned way is perfect to use. This would create a new list which contains each member of the set.

s = set([1, 2, 3])

list(s)[0]

image

Related questions

0 votes
1 answer
asked Aug 15, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 22, 2019 in Python by Eresh Kumar (45.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...