pythonlistloops

Looping through a list and assigning values has no effect


I have a list and want to change its elements

list = ['apple','potato']

Now, while this works

for i in range(list):
    list[i] = list[i].capitalize()

this one doesn't and I just don't get why

for i in list:
    i = i.capitalize()

I'm new to Python, my only background is C++ so I'm still trying to adapt to Python's style.


Solution

  • Assigning in the loop will create a new name i inside the for that loses its value after each iteration.

    That isn't really the point here though. You can have the effect get noticed if you were dealing with mutable substructures that can be altered in-place, i.e:

    l = [[1], [2]]    
    for i in l:
        i.append(2)
    

    changes will get reflected accordingly (sub-list will be get 2 appended to them).

    in your case, though, you have strs which are immutable objects. i.capitalize(), acting on a str instance will create a new copy of the value which is assigned and then lost. It will not affect the objects inside the list.

    The value i in for i in container: does refer to the objects contained in the sequence. When you assign i to the result of i.capitalize(), the name i will now refer to the new capitalized instance returned.

    Don't try and draw parallels between C++ and Python, I know it sometimes makes learning easier but, other times, in can confuse the hell out of you.

    Mandatory note: don't use list as a name, it masks the built-in name list.