Kevin Buzzard
Kevin Buzzard

Reputation: 537

How to access an attribute of an arbitrary element of a set

I have a non-empty set S and every s in S has an attribute s.x which I know is independent of the choice of s. I'd like to extract this common value a=s.x from S. There is surely something better than

s=S.pop()
a=s.x
S.add(s)

-- maybe that code is fast but surely I shouldn't be changing S?

Clarification: some answers and comments suggest iterating over all of S. The reason I want to avoid this is that S might be huge; my method above will I think run quickly however large S is; my only issue with it is that S changes, and I see no reason that I need to change S.

Upvotes: 1

Views: 88

Answers (1)

DSM
DSM

Reputation: 353019

This is almost but not quite the same as this question on getting access to an element of a set when there's only one-- there are solutions which apply there which won't work here, and others which work but are inefficient. But the general trick of using next(iter(something_iterable)) to nondestructively get an element still applies:

>>> S = {1+2j, 2+2j, 3+2j}
>>> next(iter(S))
(2+2j) # Note: could have been any element
>>> next(iter(S)).imag
2.0

Upvotes: 2

Related Questions