Is there a general rule for when a list comprehension is preferred over a for loop? For example:
A single for loop is great when converted to a comprehension:
l = []
for word in sentence:
l.append(word)
# [word for word in sentence]
A double one might be too:
l = []
for word in sentence:
for letter in word:
l.append(letter)
# [letter for word in sentence for letter in word]
However, I think the readability gets pretty poor after that. For example, with ifs:
l = []
for word in sentence:
if word.startswith('u'):
for letter in word:
if letter in ('a', 'b', 'c', 'o'):
l.append(letter)
# [letter for word in sentence if word.startswith('u') for letter in word if letter in ('a', 'b', 'c', 'o')]
Is there a suggestion for the complexity of a for loop pattern where it would be worse trying to put it into a list comprehension?
lfor list because it looks too much like1:)