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

前端 未结 14 2616
孤城傲影
孤城傲影 2020-12-07 07:17

Suppose the following:

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

How do I get a value (any value) out of s without doing s.pop()

14条回答
  •  眼角桃花
    2020-12-07 07:47

    Seemingly the most compact (6 symbols) though very slow way to get a set element (made possible by PEP 3132):

    e,*_=s
    

    With Python 3.5+ you can also use this 7-symbol expression (thanks to PEP 448):

    [*s][0]
    

    Both options are roughly 1000 times slower on my machine than the for-loop method.

提交回复
热议问题