How to transform this for loop in a list comprehension?

Question:

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
Asked By: EGS

||

Answers:

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
Answered By: Ahmed Abo alhija

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.

Answered By: Guimoute
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.