Home > Blockchain >  Python - SUM(Iterator, FOR Loop) - How does this work?
Python - SUM(Iterator, FOR Loop) - How does this work?

Time:01-11

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

CodePudding user response:

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.

CodePudding user response:

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]

CodePudding user response:

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]
  • Related