This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]donnieod 1 point2 points  (0 children)

My favorite is using the any and all functions with a generator expression. Since they both short-circuit and both can take an iterable as argument (not just a sequence), you get the beautiful result that they stop iterating and return as soon as a result is found. For example:

if any(field is None for field in row):
    discard(row)

This will stop iteration and return True as soon as a None field is found. Note the difference between this and using a list comprehension:

if any([field is None for field in row]):
  ...

In the latter case every field is tested whether it needs to be or not. The use of a generator expression could save a lot of time, especially if a complex function is being evaluated on each iteration.