Can you break down the uses of the temporary variable `word` in the example?

@ca_puar, thanks for your helpful explanation! I will be saving that explanation to my notes.

In fact, in testing this feature, I observed that the condition does not even have to be direclty related to the current element of the iterable_list

list = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]
usernames = []

usernames = ["Trees" for a in list if len(list) > 4 ]

Print(usernames)

returns:

['Trees', 'Trees', 'Trees', 'Trees', 'Trees', 'Trees', 'Trees', 'Trees']

Granted, the comprehension is not needed in this case, since the code could be generated with a simple for loop - but the code runs nevertheless.

This behavior is the same as “normal” loop, you can set different conditions and append what-ever you like. The list comprehension is just a short-hand in that regard

1 Like