1

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.

Kevin Buzzard
  • 537
  • 4
  • 11
  • I'm not exactly sure what you're going for, but could something like `[x.x for x in S]` work? – Daniel Robertson Mar 14 '15 at 01:33
  • 1
    Sure that would work (and then I could just just take the 0th element of that list), but what if `S` has a million elements? Why iterate over all of them when the answer is in the first one I find? Note that `s.x` is the same for every element `s` of `S`. – Kevin Buzzard Mar 14 '15 at 10:06
  • You're right, wasn't exactly sure what you were going for. – Daniel Robertson Mar 14 '15 at 12:58

1 Answers1

2

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
Community
  • 1
  • 1
DSM
  • 342,061
  • 65
  • 592
  • 494