4 ms·
`every` and `some` can be emulated by composing `map` (or a listcomp) with the builtin `any` and `all` (which, for some reason, don't take an optional predicate
by smanek 17y ago
`every` and `some` can be emulated by composing `map` (or a listcomp) with the builtin `any` and `all` (which, for some reason, don't take an optional predicate)
No they can't - this version wouldn't short circuit evaluation, which is completely the wrong behavior. Map would have to apply the predicate to every element of the list before any/all kicked in.
As a trivial example, consider I had a million item list and want to find out if every element is prime. If 8 is the first element, 'every' would return false after looking at the first item - while your composition would apply the prime predicate to all million elements (which would be ridiculously slow ...) before even starting to apply 'all' (which would short circuit, after seeing the first false).
- knome 17y agoIf you have enough elements to desire short circuit evaluation you can, as `masklinn` mentioned, use a list comprehension. Specifically a generator list comprehension. http://www.python.org/dev/peps/pep-0289/ http://www.python.org/dev/peps/pep-0289/ big_list = make_big_list() if any( not prime( a ) for a in big_list ) : do_thing() When you surround the list comprehension syntax with parenthesis instead of square brackets, either as a lone argument to a function or independently, you create a generator that will iterate once over the given data. This allows for functions accepting sequences to short circuit without completing the function mapping.
- masklinn 17y ago> No they can't - this version wouldn't short circuit evaluation, which is completely the wrong behavior. Map would have to apply the predicate to every element of the list before any/all kicked in. Just use the lazy map itertools.imap (or Python 3, where `map` is lazy) or replace listcomps by gencomps, any & all take any iterable if you're worried about that. Stop creating problems where there is none.