Carl Banks wrote: > Here's another reason not to use "if lst". Say you have a function > that looks like this: > > def process_values(lst): > if not lst: > return > do_expensive_initialization_step() > for item in lst: > do_something_with(item) > do_expensive_finalization_step() > > That works, right? No problem, right? > > What if you called the function like this: > > process_values(x.strip() for x in values_lst) > > Oops, now we've just gone through an expensive initialization and > finalization for nothing (since values_lst was empty). Maybe some > subtle bugs introduced. If we're lucky, the finalization step will > throw an exception. > > If we had used "if len(list)>0", we'd have gotten a nice exception > telling us that a generator is not welcome. Then we'd have changed the > argument to a list comprehension, or better, changed the function to > work for any iterator.
The argument that one should always use len() to test whether sequences are empty or not simply because the use of len() gives a free "is it a sequence?" type-check is not apt to be well received by an audience which rejects explicit type-checking in general. The specific example given, where a lack of a len() works correctly, except for using more execution time on generators than on lists, is not apt to be well received by an audience which rejects premature optimizations in general, and which believes that if you don't notice a speed problem, it doesn't exist, and if you _do_ notice a speed problem, the profiler is the best tool to attack it with. The perverse wish, expressed in the specific example, that SOME piece of code SOMEWHERE should PLEASE throw an exception because some idiot passed a generator expression rather than a list into a function, is not apt to be well received by an audience which strives for generality when it makes sense; and I daresay most members of that audience, if confronted with the wished-for exception, would fix the function so that it quite happily accepted generator expressions, rather than changing a conditional to use len() just so that an equivalent exception could happen a bit earlier. I'm not saying that _everybody_ on this list is in any of these audiences, but I would suspect that all the people arguing with you are :) Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list