-1

I am trying to transform a for loop in a list comprehension but I keep getting a syntax error. What am I doing wrong?

The for loop:

for item in items:
    if item in default_items.keys():
        total += default_items[item]
    

The list comprehension:

[total := total + default_items[item] if item in default_items.keys() for item in items]

Here some example of the code in context:

items = []
total = 0
default_items = {"tophat": 2, "bowtie": 4, "monocle": 5}
items.append("bowtie")
items.append("jacket")
items.append("monocle")
items.append("chocolate")

for item in items:
    if item in default_items.keys():
        total += default_items[item]
        
print(total) # 9

items = []
total = 0
[total := total + default_items[item] if item in default_items.keys() for item in items] # raising sintax error

print(total) # 9
EGS
  • 409
  • 4
  • 23
  • The `if` should be ***after*** the `for`: `[total := ... for item in items if item ...]`. If you use it like that, it also needs an `else` part – Tomerikoo Mar 14 '23 at 10:36
  • Also please see [Is it Pythonic to use list comprehensions for just side effects?](https://stackoverflow.com/q/5753597/6045800). You are not actually building a list, so why are you using ***list***-comprehension? – Tomerikoo Mar 14 '23 at 10:38

2 Answers2

3

I'm not sure why you are summing manually in your list comprehension approach, just use sum:

total = sum(default_items.get(item, 0) for item in items)

You also do not need to check if the item is in the default_items dict because .get(item, 0) will both get the item if it's available and not affect the sum if it's not.

Guimoute
  • 4,407
  • 3
  • 12
  • 28
-4
if __name__ == '__main__':
    items = []
    total = 0
    default_items = {"tophat": 2, "bowtie": 4, "monocle": 5}
    items.append("bowtie")
    items.append("jacket")
    items.append("monocle")
    items.append("chocolate")

    for item in items:
        if item in default_items.keys():
            total += default_items[item]

    print(total)  # 9

    total = 0
    tt = [default_items[item] for item in items if item in default_items.keys()]

    print(sum(tt))  # 9