pythonlistsetlist-comprehensionset-comprehension

How to get listcomprehension result as unpacked list


I have a function (in the example: some_function()) that returns a set. I got a data structure of some elements (in the example arr) and need to map the elements to the function and I want to get back a set of all elements. Not a set of sets but a set of all the elements that are in the sets. I know that some_function() only returns one dimensional sets.

I tried to use map but didn't quite get it to work, I got it to work with list comprehensions but I don't really like my solution.

Is it possible to not create a list and then unpack it?
Or can I somehow convert what I get from my map approach without much work?

Example:

arr = [1, 2, 3]

# I want something like this
set.union(some_function(1), some_function(2), some_function(3))

# where some_function returns a set    

# this is my current solution
set.union(*[some_function(el) for el in arr]))

# approach with map, but I couldn't convert it back to a set
map(some_function, arr)

Solution

  • You can use a generator expression instead of a list comprehension so that you don't have to create a temporary list first:

    set.union(*(some_function(el) for el in arr)))
    

    or, using map:

    set.union(*map(some_function, arr))