Programming-Idioms

History of Idiom 43 > diff from v48 to v49

Edit summary for version 49 :
[Python] fixed code in case of exception

Version 48

2020-01-09, 17:05:16

Version 49

2020-01-09, 17:07:28

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
Imports
from itertools import chain
Imports
from itertools import chain
Code
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
print(next(i for i in chain(*matrix) if i < 0))
Code
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
	print(next(i for i in chain(*matrix) if i < 0))
except StopIteration:
	pass
Comments bubble
We make a generator that will return negative values from a list (and use chain(*matrix) to flatten the 2d list into a 1d list) and only take one value from it with the next function.

This will raise StopIteration if it doesn't find the value.
Comments bubble
We make a generator that will return negative values from a list (and use chain(*matrix) to flatten the 2d list into a 1d list) and only take one value from it with the next function.

This will raise StopIteration if it doesn't find the value so we need to account for it.
Demo URL
https://ideone.com/0Bo95p
Demo URL
https://ideone.com/0Bo95p