Programming-Idioms

History of Idiom 43 > diff from v47 to v48

Edit summary for version 48 :
[Python] fixed explanation

Version 47

2020-01-09, 17:04:10

Version 48

2020-01-09, 17:05:16

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]]
print(next(i for i in chain(*matrix) if i < 0))
Comments bubble
We make a generator that will return negative values from a list (and use chain(*matrix) to expand the 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.
Demo URL
https://ideone.com/0Bo95p
Demo URL
https://ideone.com/0Bo95p