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:
- You don't actually want a list
- The logic is too long
Case 1: You don't actually want a list
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)
Case 2: The logic is too long
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.
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: if len(team.roster) <= 1: continue for player in team.get_players(): if player.is_injured(): continue account = player.get_account() active_player_accounts.append(account)
This is clearer because we can:
- Include comments to explain the code.
- Use control flow keywords like continue.
- Debug this section of code more easily using logging statements or asserts.
- Easily see the complexity of the code by scanning down the lines, picking out for loops.