1

For example, when adding lists together:

list = [1,2,3,4,5]

list_sum = 0
for x in list:
   list_sum += x
Οurous
  • 348
  • 6
  • 17
Joe
  • 31
  • 1
  • 1
  • 2

3 Answers3

2

list_sum += x means add the contents of list_sum variable with the contents of variable x and again store the result to list_sum variable.

Code explanation:

list_sum = 0     # At first, 0 is assigned to the `list_sum` variable .
for x in list:   # iterating over the contents which are present inside the variable `list`
list_sum += x    # list_sum = 0+1 . After the first iteration, value 1 is stored to list_sum variable. Likewise it sums up the values present in  the list and then assign it back to list_sum variable. Atlast `list_sum` contains the sum of all the values present inside the given list.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

It's shorthand for list_sum = list_sum + x

for x in list: will loop once through every element in list, assigning the value to a temporary variable x

Check out these duplicates:

Duplicate 1and not exactly a duplicate but another example of how it works

Erick
  • 2,488
  • 6
  • 29
  • 43
  • 1
    "It adds an element" is kind of confusing. You should change how you word this. – mash Oct 31 '14 at 01:13
  • Fair enough, reworded it. – Erick Oct 31 '14 at 01:17
  • 2
    It's not exactly the same as `list_sum = list_sum + x`. That implies that a new object is created and then assigned to the name `list_sum`. This is true for immutable objects, but for mutable objects `+=` is an in-place operator and modifies the existing object. The main difference being that other references will also se the change. eg. `x = []; y = x; y += [1]; assert x == y`, whereas `x = 0; y = x; y += 1; assert x != y`. – Dunes Oct 31 '14 at 01:21
-1

It is shortened operation used in any language list_sum += x => list_sum = list_sum + x
There can also be "-=", "*=" and "/=" respectively.

Bozic
  • 159
  • 1
  • 12