Preferred Python way of getting the item of a set with a length(/cardinality) of one without removing it?

StackOverflow https://stackoverflow.com/questions/6091922

Pergunta

Given set s, which of the segments below looks better?

if len(s) == 1:
    v = s.copy().pop()
    # important stuff using variable v takes place here

or

if len(s) == 1:
    v = s.pop()
    s.add(v)
    # important stuff using variable v takes place here

or

if len(s) == 1:
    for v in s:
        # important stuff using variable v takes place here

I guess the last segment is the most efficient, but doesn't it look silly to use a loop that never actually loops?

Why don't python sets have an alternative method to pop that doesn't remove the item?

This may seem like a trivial question, but as I've run into this scenario multiple times it has become an itch in need of scratching!

Foi útil?

Solução

You can assign the only element to v like this:

(v,) = the_set

It raises a exception if the_set doesn't contain exactly one item.

Outras dicas

Why don't python sets have an alternative method to pop that doesn't remove the item?

If you want to access the first (and only) item without changing the set structure, use an iterator:

v = iter(s).next()

This works prior to Python 3. In Python 3, you need to use the built-in next function:

v = next(iter(s))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top