This is the exact question which has been answered in detail on this site called Interview Cake. Following the detailed answer, sourced from here.
Two common cases where you shouldn't use a list comprehension are:
List comprehensions build lists, but that's not the only reason we use for loops. Sometimes we have functions or methods whose main purpose is their side effect, and they don't return anything meaningful.
[team.set_location(HOME) for team in league_teams if team in home_teams_today]
Not only does this look more natural as a conventional for loop, it doesn't waste space creating a list that it just ignores.
for team in league_teams:
if team in home_teams_today:
team.set_location(HOME)
One of the main benefits of list comprehensions is that they make your code shorter and clearer. Once you start packing too much into a single statement, it becomes harder to follow than a regular for loop.
For example:
active_player_accounts = [player.get_account() for team in league_teams
if len(team.roster) > 1 for player in team.get_players()
if not player.is_injured()]
While descriptive variable names went a long way into making this piece of code somewhat readable, it's still hard to understand.
active_player_accounts = []
for team in league_teams:
# teams need to have at least 2 players before they're considered "active"
if len(team.roster) <= 1:
continue
for player in team.get_players():
# only want active players
if player.is_injured():
continue
account = player.get_account()
active_player_accounts.append(account)
This is clearer because we can: