E-man
E-man

Reputation: 167

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):

for i in range(0, 9):
    for j in range(0, 9):
        if self.get(i)[j] == "1":
            return (i, j)

Upvotes: 1

Views: 366

Answers (1)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24163

>>> next(((i, j)
           for i in range(0, 9)
           for j in range(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.

Upvotes: 2

Related Questions