S
Steven D'Aprano
Steven D'Aprano said: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