On Sat, 01 Apr 2006 08:12:25 -0300, Felipe Almeida Lessa wrote: > Em Sáb, 2006-04-01 às 20:44 +1000, Steven D'Aprano escreveu: >> Here's another way of doing it: >> >> lst = [2, 4, 42] >> any(map(lambda x: x==42, lst)) > > In fact, as we're talking about Python 2.5 anyway, it would be better > not to waste memory and use: > > any(x == 42 for x in lst)
You might be talking about Python 2.5, but I certainly am not. any() and all() are easy to (almost) implement in earlier Python versions: try: any except NameError: # warning: this version will consume an iterator def any(seq): for s in seq: if s: return True return False and similarly for all(). In any case, I question your assumption that the version using map must automatically "waste memory". Iterators carry a certain amount of overhead which lists do not. For small enough lists, that overhead will be smaller than the extra memory used by the list. "Small enough" will depend on the type of objects involved: big complex objects created on the fly by the generator gives the generator the advantage, small simple objects like ints give the list the advantage. As Python doesn't give us any way to measure the memory used by an object, it is hard to say where that cut-off lies, but my wild guess is that for ints, it would probably be in the multiple tens. But then, unless these are big complex objects, why are we micro-optimizing our code anyway? I'm running a Python process, and it is consuming 6.7MB of memory at the moment. Do I really care about saving 80 or 100 bytes?, or even 100 kilobytes? I don't think so. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list