Python for loop

Hey guys I have question four you.

I have this.

prices = [30, 25, 40, 20, 20, 35, 50, 35]
total_price = 0

total_price += [price for price in prices]
print(total_price)

This does not work. Apparently I can not use += with list or something.

So I did it the other way.

prices = [30, 25, 40, 20, 20, 35, 50, 35]
total_price = 0

for price in prices:
  total_price += price 
print(total_price)

I have achieved what I wanted but I am curious if there is some way to make less complicated as in first case. Is there something that I can do with first code so I can make it work it that way?

here:

[price for price in prices]

you use list comprehension, which generates a list identical to the one you already have.

we can use + with list, which results in list extension:

print([1, 2, 3] + [4, 5, 6]) // [1, 2, 3, 4, 5, 6]

I think the other way you solved the exercise is good.

Hi, @bit5955278864,

You could this, if you wish to include a list comprehension, though you don’t really need one …

prices = [30, 25, 40, 20, 20, 35, 50, 35]
print(sum([price for price in prices]))

Output:

255

… or, even better, without the list comprehension …

print(sum(prices))

If you need to have the total_price variable, do this …

total_price = sum(prices)

The above assume that you wish to compute a total of all the prices.

Edited on August 18, 2020 to provide some additional examples

1 Like