3 ms·
def flatmap(f, items): return itertools.chain(*map(f, items)) 1. in Python 2 `map` is eager which — as with the previous `even` filter — may lead to un
by masklinn 14y ago
def flatmap(f, items):
return itertools.chain(*map(f, items))
1. in Python 2 `map` is eager which — as with the previous `even` filter — may lead to unnecessary work if you only need part of the list (or a dead process if the input is infinite...). itertools.imap (or a generator comprehension) would be better. This is "fixed" in Python 3 (where the `map` builtin has become lazy and `itertools.imap` has been removed) but
2. it's being eagerly unpacked through *, itertools.chain also provides a from_iterable method which doesn't have that issue (and can be used to flatten infinite streams), introduced in 2.6
So `flatmap` would probably be better as:
def flatmap(f, items):
return itertools.chain.from_iterable(
itertools.imap(
f, items))
- naiquevin 14y agoThanks for the corrections. I have made an edit (although not sure how long it will take to clear the github-pages cache)