-2

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. If this kind of question had already been asked, please, feel free to redirect me and close this topic. Thank you!

Machavity
  • 29,816
  • 26
  • 86
  • 96
user3002386
  • 125
  • 1
  • 8
  • 5
    Because doing so doesn't update the list. Only the variable i is changed. – Gurupad Mamadapur Dec 21 '16 at 13:17
  • 2
    As you iterate through the `for` loop, the variable `i` takes the _value_ of each element in the list. It is not a _reference_ to each point in the list. It is a separate variable. If you reassign it, you are only affecting the variable `i`. – khelwood Dec 21 '16 at 13:18
  • So it's kind of a right value? – user3002386 Dec 21 '16 at 13:19
  • do `lst = [x.capitalize() for x in lst]` (avoid `list` as it is the list type) – Jean-François Fabre Dec 21 '16 at 13:20
  • Possible duplicate of [strange result when removing item from a list](http://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list) – Will Dec 21 '16 at 13:20

1 Answers1

1

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.

Dimitris Fasarakis Hilliard
  • 136,212
  • 29
  • 242
  • 233