Skip to content Skip to sidebar Skip to footer

Efficient Double For Loop

What is the most efficient (or Pythonic way) to carry out a double for loop as in below (I know how to do this for list comprehension but not for a single object to be returned): f

Solution 1:

>>> next(((i, j)
           for i inrange(0, 9)
           for j inrange(0, 9)
           if self.get(i)[j] == "1"), None)

This will return None if nothing is found.

See the documentation for next.

The first parameter is a generator. You need this if you supply None as the second parameter. Otherwise you can skip the extra parentheses. If you don't supply None though it will throw a StopIteration exception if nothing is found.

Post a Comment for "Efficient Double For Loop"