When should you NOT use list comprehensions in Python?

List comprehensions in Python help me write "pythonic" code; are there instances where you prefer an alternate way of writing lists?

Comments (1)

Add a comment
Maria Charman's photo

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.

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:

  • 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.