Why does += add the sum int. of one list to another and not just +?

Viewed 169

I have the following code:

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
scoops_sold = 0

I originally wrote:

for location in sales_data:
  print(location)
  for element in location: 
    scoops_sold + element 
    print(scoops_sold) 

After messing around I saw I was just missing an = after the + sign.

Why does += add the sum int. of one list to another and not just +?

2 Answers

Currently, all of the previous answers, including the accepted answer, are entirely misleading, note the difference between these two different python constructs:

  1. The + operator, generates a new list from the two operands:

    >>> a = b = [1]
    >>> a = a + [2]
    >>> a, b
    [1, 2], [1]
    

    Here, both a and b are initially pointing to the same list. Then we have created a new list and rebound it to the variable a

  2. The += operator, modifies an existing list

    >>> a = b = [1]
    >>> a += [2]
    >>> a, b
    [1, 2], [1, 2]
    

    Here, both a and b are initially pointing to the same list. Then we have modified this same list.

The takeaway ... the syntax a = a + b is not short for a += b

+= is short for scoops_sold = scoops_sold + element. Having scoops_sold + element is computing the result but not storing it to any variable where as scoops_sold = scoops_sold + element is computing the result and assigning it to scoops_sold.

Related