Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve an element from a set without removing it?

Tags:

python

set

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.

like image 527
Daren Thomas Avatar asked Sep 12 '08 19:09

Daren Thomas


People also ask

How do you take an element from a set?

The remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.

How do you get the first element of a set in Python?

We can access the first item in the set by using iter() function, we have to apply next() to it to get the first element.

How do you slice a set in Python?

Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.


1 Answers

Two options that don't require copying the whole set:

for e in s:     break # e is now an element from s 

Or...

e = next(iter(s)) 

But in general, sets don't support indexing or slicing.

like image 141
Blair Conrad Avatar answered Sep 18 '22 20:09

Blair Conrad