0

I have a situation in my code where there is a Frozenset which contains a single number (e.g. Frozenset([5])). What I want to do is get that value into a variable. What is the pythonic way to do this?

Since you can iterate over a Frozenset, I have already tried to do it like this: var = next(myFrozenSet) but it does not work, since a Frozenset is not actually an iterator. I also tried to use myFrozenSet.pop(), but this is not attribute of Frozensets.

martineau
  • 119,623
  • 25
  • 170
  • 301
micsthepick
  • 562
  • 7
  • 23

1 Answers1

3

You can create an iterator with the iter() function:

element = next(iter(some_frozen_set))

This is the most efficient method of getting a single element out of a frozenset; all other methods involve creating another container first (like a set or list), which is more costly than creating an iterator.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • In another place I want to reverse iterate over the `frozenset`, is the best way to do this by creating a container first? – micsthepick Mar 14 '17 at 01:35
  • @micsthepick: sets have no order, so there is no forward or reverse direction. You'd *have* to create an ordered container for the elements first, imparting some kind of sorting in the process. – Martijn Pieters Mar 14 '17 at 01:36