0

In python 3, I have a function that returns a list of variable size

I would like to run this function over a list and concatenate the results. for example::

def the_func(x):
    return [x]*x

def mapvar(f,v):
    ans=[]
    for x in v:
        ans.extend(f(x))
    return ans

print (mapvar(the_func,range(10)))

Is there a best practice in python to do this? if is there a standard mapvar function?

yigal
  • 3,923
  • 8
  • 37
  • 59

2 Answers2

1

What you've got looks good. I would just factor out flatten and use the builtin map.

def the_func(x):
    return [x] * x

def flatten(lst):
    return [x
        for subl in lst
            for x in subl]

print(flatten(map(the_func, range(10))))
axblount
  • 2,639
  • 23
  • 27
1

Since the question is tagged [python-3.x], here is a one-liner using map for projection and itertools.chain.from_iterable for flattening:

import itertools
result = list(itertools.chain.from_iterable(map(the_func, range(10))))
print(result)

This is about 1 second faster than the nested for list comprehension version (3.3 seconds vs. 4.1 second) on average using 1 mil. iterations.

MEE
  • 2,114
  • 17
  • 21
  • @yigal You may also want to look at: [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) for a comparison of different flattening approaches. – MEE Dec 11 '18 at 15:58