Why bool( object )?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri May 1 04:33:08 EDT 2009
On Fri, 01 May 2009 00:22:22 -0700, Paul Rubin wrote:
> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:
>> for x in a or b or c:
>> do_something_with(x)
>
> Ugh!!!!
>
> for x in [a,b,c]:
> if len(x) > 0:
> do_something_with(x)
> break
What ugly, wasteful code. And it's *wrong* -- it doesn't do what my code
does.
(1) Why build a list [a, b, c] that you don't need?
(2) Why assume that a, b and c are sequences with a fast __len__ method?
They might be (say) linked lists that take O(N) to calculate the length,
or binary trees that don't even have a length, but can be iterated over.
(3) And your code is wrong. I pass each element of the first non-empty
sequence to do_something_with(). You pass the entire sequence. To do what
my code does, you would need a nested for-loop like this:
for seq in [a,b,c]:
if len(seq) > 0:
for x in seq:
do_something_with(x)
break
--
Steven
More information about the Python-list
mailing list