Is there a way to collapse multiple_get into as few lines as possible?

def single_get(target):
    return [some list of objects] # might be an empty list 

def multiple_get(targets):
    result = []
    for target in targets:
    return result
  • 3
    \$\begingroup\$ This code looks a bit sketchy. Please fill it in with real code so that we can advise you properly. \$\endgroup\$ – 200_success Jun 12 '16 at 5:29

Look into the itertools library in general, for list-and-sequence-manipulating commands. You're looking for a way to "flatten" a list of lists; itertools calls this itertools.chain.

def multiple_get(targets):
    return list(itertools.chain.from_iterable(single_get(target) for target in targets))

However, Python can do it natively as a nested list comprehension:

def multiple_get(targets):
    return [r for target in targets for r in single_get(target)]
| improve this answer | |
  • 2
    \$\begingroup\$ If you prefer functional programming style to list comprehensions, you could also use itertools.chain(map(single_get, target)). \$\endgroup\$ – David Foerster Jun 12 '16 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.