I am trying to create an inmmutable object, specifically a frozenset, from a list after applying some function foo() to all of it's elements. That is to say:
my_list = ['a_1', 'a_2', ... , 'a_n']
given the list my_list, what i want to do is execute over all the elements the function foo() and with the result build a frozenset. Something like this:
my_list = frozenset([foo('a_1'), foo('a_2'), ... , foo('a_n')])
I don't know if there is any way to do this in a single pass, because if I am not mistaken, for the creation of the frozen set, we iterate on the elements of the list, which if we add the iterative application of the foo() function, gives me two passes, where my intuition tells me that it could be done in one.
Is there any way to do this by taking advantage of the iteration for the set creation?
Sure, if you want a single pass, use a generator, or in this case, map
fits perfectly:
frozenset(map(foo, my_list))
Or with a generator, using a generator expression:
frozenset(foo(x) for x in my_list)