"and" and "or" on every item in a list
Matimus
mccredie at gmail.com
Mon Oct 29 19:15:15 EDT 2007
More information about the Python-list mailing list
Mon Oct 29 19:15:15 EDT 2007
- Previous message (by thread): emacs lisp as text processing language...
- Next message (by thread): "and" and "or" on every item in a list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Oct 29, 3:57 pm, GHZ <geraint.willi... at gmail.com> wrote: > Is this the best way to test every item in a list? > > def alltrue(f,l): > return reduce(bool.__and__,map(f,l)) > > def onetrue(f,l): > return reduce(bool.__or__,map(f,l)) > > > > >>> alltrue(lambda x:x>1,[1,2,3]) > False > > >>> alltrue(lambda x:x>=1,[1,2,3]) > True > > Thanks If you are using python 2.5 the best way would be something like this: >>> all(x > 1 for x in [1,2,3]) False >>> any(x > 1 for x in [1,2,3]) True If you are using an earlier version you are still discouraged from using reduce in place of a more readable construct. In most cases list comprehension is encouraged over map also. If `all' and `any' aren't defined you can use something like the following. One advantage of these over what you posted is that they will return as soon as an exit condition is reached as opposed to processing the entire list. [code] if not all: def all(seq): for val in seq: if not val: return False return True if not any: def any(seq): for val in seq: if val: return True return False [/code] Matt
- Previous message (by thread): emacs lisp as text processing language...
- Next message (by thread): "and" and "or" on every item in a list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list