Search code examples
pythonpython-3.xlistincrement

Why can I not increment a list this way in Python?


Language is Python. I am trying to add 'a' to all of the values in a list 'sumarr'.

Here is my code:

for b in sumarr:
    b+=a

Why does this not work? I know I can use list comprehensions like this:

sumarr = [b+a for b in sumarr]

But why does the first method not work?


Solution

  • b is a local variable - a reference of the list item, not the actual item in list.

    If you do print( b += a ) you will see the expected number, but it won't put that result back into your list.

    #! /usr/bin/env python3
    
    sumarr = [1, 2, 3, 4]
    a = 3
    
    for b in range( len(sumarr) ):
        sumarr[b] += a
    
    for b in sumarr:
        print( b )
    

    4
    5
    6
    7