EP 8 Avoid More Than Two Expression in List Comprehensions

  • List comprehensions support multiple levels of loops and multiple conditions per loop level

Effective Python

>>> matrix = [[1,2,3], [4,5,6], [7,8, 9]]
>>> flat = [ x for row in matrix for x in row]
>>> flat
[1, 2, 3, 4, 5, 6, 7, 8, 9]

multiple condition

>>> filtered = [[x for x in row if x % 3 == 0] for row in matrix if sum(row) >= 10]
>>> filtered
[[6], [9]]

Recommended Posts

EP 8 Avoid More Than Two Expression in List Comprehensions
Effective Python Memo Item 8 Avoid three or more expressions in list comprehensions
List comprehensions are no longer slow in PyPy 7.3.1