3

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)
mxcxx
  • 33
  • 3

3 Answers3

2

I think your current solution is fine. If you want to avoid creating a list, you may try:

set.union(*(some_function(el) for el in arr)))
Sorawee Porncharoenwase
  • 6,305
  • 1
  • 14
  • 28
2

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))
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

In Python, sometimes you just have to not be fancy.

result = set()

for el in arr:
    result.update(some_function(el))

This approach doesn’t create a list of the return values and so doesn’t hold onto sets longer than necessary. You can wrap it in a function for cleanliness.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • You can use `functools.reduce(set.union, map(some_function, arr))` as well to avoid holding many sets in memory. This also works if you replace the call to `map` with a generator expression like `(some_function(el) for el in arr)`. – chepner Feb 01 '19 at 21:04
  • @chepner: That’s O(n²) because it copies the set every time, isn’t it? – Ry- Feb 01 '19 at 21:05
  • Hmmm, probably. – chepner Feb 01 '19 at 21:09