Programming-Idioms

History of Idiom 43 > diff from v45 to v46

Edit summary for version 46 :
[Python] Using enumerate is the pythonic way to iterate while keeping the index

Version 45

2019-09-26, 17:38:12

Version 46

2019-09-27, 03:20:25

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Illustration

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Illustration
Code
def loop_breaking(m, v): 
     position = None 
     for row in range(len(m)): 
         for column in range(len(m[row])): 
             if m[row][column] == v: 
                 position = (row, column) 
                 return position
     return position

print(loop_breaking(([1,2,3],[4,5,6],[7,8,9]), 6))
Code
def loop_breaking(m, v): 
    for i, row in enumerate(m): 
        for j, value in enumerate(row): 
            if value == v: 
                return (i, j)
    return None

print(loop_breaking(([1,2,3],[4,5,6],[7,8,9]), 6))
Comments bubble
Rather than set break flags, it is better to refactor into a function, then use return to break from all nested loops.
Comments bubble
Rather than set break flags, it is better to refactor into a function, then use return to break from all nested loops.