Effective Python Memo Item 8 Avoid three or more expressions in list comprehensions

** Notes on Effective Python ** Item 8: Avoid more than one expression in list comprehensions (p16-18)

Two or more for statements can be written in the comprehension notation

#Output the contents of the matrix to one list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print(flat)

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Convenient! Let's do a little complicated processing

#Leave the procession and square all the contents
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
squared = [[x ** 2 for x in row] for row in matrix]
print(squared)

>>>
[[1, 4, 9], [16, 25, 36], [49, 64, 81]]

Yeah, it's a little complicated but still readable Let's add another loop!

#Output the contents of a 3D matrix into a single list
my_list = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
flat = [x for sublist1 in my_list for sublist2 in sublist1 for x in sublist2]
print(flat)

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

It became very hard to see. At this point, there is almost no merit of inclusion notation. Let's write with a normal for statement

#Write in a normal for loop
my_list = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
flat = []
for sublist1 in my_list:
    for sublist2 in sublist1:
        flat.extend(sublist2)   #It's not append!

print(flat)

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

This will have longer lines, but it will be more readable than the previous description. The most important thing is readability rather than the number of lines!

Recommended Posts

Effective Python Memo Item 8 Avoid three or more expressions in list comprehensions
Effective Python Memo Item 9 Consider generator expressions for large comprehensions
Effective Python Memo Item 3
EP 8 Avoid More Than Two Expression in List Comprehensions
Effective Python Memo Item 11 Use zip to process iterators in parallel
OR the List in Python (zip function)
Effective Python memo Item 10 Enumerate from range
Effective Python memo Item 7 Use list comprehension instead of map and filter
Sorted list in Python
Python> list> extend () or + =
Filter List in Python
Python3 List / dictionary memo
[Memo] Python3 list sort
Indent comprehensions in Python
List find in Python
Effective Python Memo Item 19 Give optional behavior to keyword arguments
Effective Python Note Item 16 Consider returning a generator without returning a list
Multiple regression expressions in Python
Use regular expressions in Python
Wrap long expressions in python
Avoid KeyError in python dictionary
Avoid multiple loops in Python
Python list comprehensions and generators
Getting list elements in Python
A memo that handles double-byte double quotes in Python regular expressions