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
  • 112,593
  • 23
  • 157
  • 280
micsthepick
  • 555
  • 6
  • 21

1 Answers1

2

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
  • 963,270
  • 265
  • 3,804
  • 3,187
  • 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