0

I am continuing my learning journey on Python and came across a snippet of code that I am quite confused as to how it works regarding the SUM() function in Python.

The code is as follows

prices = {'apple': 0.75, 'egg': 0.50}
cart = {
  'apple': 1,
  'egg': 6
}

bill = sum(prices[item] * cart[item]
           for item in cart)

print(f'I have to pay {bill:.2f}')

The final output of this is "I have to pay 3.75"

The part that really confuses me is in the SUM function with the "iterator" or the "for item in cart"

From python documentation on the SUM function it states

sum(iterable, [start])

Iterable: Item like string, list, dictionary etc.

Start: An optional numeric value added to the final result. It defaults to 0.

So for example if with this code

sum([1,2,3], 4)

This would basically work out to 1+2+3+4=10, which makes sense to me.

So I am confused how the "for loop" portion of the snippet of code is legal?

I tried googling around but most examples I find are pretty simple like the one I just mentioned, and I cant find any explanations on how the FOR loop works with SUM like this

rodneyc8063
  • 113
  • 8
  • 1
    Does this answer your question? [Understanding generators in Python](https://stackoverflow.com/questions/1756096/understanding-generators-in-python) – Pranav Hosangadi Jan 11 '23 at 06:05
  • @PranavHosangadi - I appreciate the suggested post though I admit it does go into greater detail then perhaps for new Python programmers like myself can wrap their head around. It also compares things to Java which is not my forte. Though at least now I know this type of code is called a "generator" and that post also mentions list comprehensions which I will need to next read up on :) – rodneyc8063 Jan 13 '23 at 22:24

3 Answers3

1

prices[item] * cart[item] for item in cart is a generator. It produces an iterable, which is what the sum function takes as its first parameter.

for item in cart iterates over each of the keys in the cart dictionary. So in this case, it will iterate over the list ['apple', 'egg'], setting item to each of these in turn. For each iteration, the expression prices[item] * cart[item] looks up the price of an item (prices['apple'] for example) and multiplies it by the quantity of an item (cart['apple'] for example). The generator produces a sequence consisting of the result of computing the value of this expression for each key in cart, and then sum takes that sequence and adds the elements of it together to come up with the final total of the items in cart.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
1

The code that's in the inside of the sum() is a generator expression which is basically syntactic sugar for creating an iterator from another iterator.

In your example the cart variable is an object of type Dictionary which is also an iterator, and the prices[item] * cart[item] part is how each item from the cart (the dictionary keys) is transformed into a new item for the result iterator.

The snippet bill = sum(prices[item] * cart[item] for item in cart) is equivalent to

bill = 0
for item in cart:
  bill += prices[item] * cart[item]
Diego Sanchez
  • 68
  • 1
  • 5
-1

Try reading about List comprehensions.
They're basically a one-liner way of writing simple for loops.
Since these create lists, you can feed them into functions that use lists (or iterables, to be more general), like sum:

list_of_nums = [1, 2, 3, 4]
list_of_squares = [num**2 for num in list_of_nums]
print(list_of_squares)
>>> [1, 4, 9, 16]
Adid
  • 1,504
  • 3
  • 13
  • 2
    There is no list comprehension in the given example. There is a generator, which is similar, but different. – CryptoFool Jan 11 '23 at 05:50
  • 1
    I never claimed there's a list comprehension in the example, I'm just saying knowing list comprehensions can help OP understand the code. – Adid Jan 11 '23 at 05:53
  • 2
    It's pretty misleading to be discussing a piece of code and trying to describe how it works, but to then throw out a term that isn't involved in that code. If you really think it's worth studying list comprehensions as apposed to generators, you should clearly state that what is in the code in question is not a list comprehension. – CryptoFool Jan 11 '23 at 05:55