<jupyter_start><jupyter_text>Item 8: Avoid More Than Two Expressions in List Comprehensions<jupyter_code># You can have several loops in one comprehension (read left to right)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
flat = [x for row in matrix for x in row] 
print(flat)

# You can do lists into lists
squared = [[x**2 for x in row] for row in matrix] 
print(squared)
# At some it is not really saving time but adds complexity to your code

my_lists = [
    [[1, 2, 3], [4, 5, 6]], 
    # …
]

flat = [x for sublist1 in my_lists 
        for sublist2 in sublist1 
        for x in sublist2]
# same as

flat = []
for sublist1 in my_lists:
    for sublist2 in sublist1: 
        flat.extend(sublist2)
# You can have expresssions after each loop
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
filtered = [[x for x in row if x % 3 == 0]
          for row in matrix if sum(row) >= 10] 
print(filtered)

# But does it still make sense? Very hard to comprehend<jupyter_output>[[6], [9]]
{'fraction_non_alphanumeric': 0.11734693877551021, 'fraction_numerical': 0.04081632653061224, 'mean_word_length': 3.174468085106383, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '653036', 'license': 'MIT', 'n_tokens_mistral': 383, 'n_tokens_neox': 348, 'n_words': 154, 'path': 'notes/Chapter_1:_Pythonic_Thinking/Item 8 Avoid More Than Two Expressions in List Comprehensions.ipynb', 'repo_name': 'johannstruongle/effective_python', 'size': '980'}