0

In Python the following code will modify the output

def changeList(string):
    strList = list(string)
    for i, char in enumerate(string):
        if char == 'a':
            strList[i] = 'b'

    return "".join(strList)
print(changeList("ab"))

prints out "bb" as expected. However the following function:

def changeList(string):
    strList = list(string)
    for i, char in enumerate(string):
        if char == 'a':
            char = 'b'

    return "".join(strList)

prints out "ab". Why does setting char work differently? I had thought that char was a pointer to string[i] but it looks like I'm misunderstand whats going on under the hood?

DWij
  • 3
  • 3
  • I suggest reading Ned Batchelders fantastic [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) – Matthias Apr 16 '20 at 17:47

2 Answers2

1

In your first for loop, by accessing strList[i] you modify the item in the list, where as in the second loop the list item gets the name tag char. Then when you do char = 'b' the name tag is taken away from the list item and applied to 'b'. The list item itself is not modified, so the list is returned unchanged.

Erich
  • 1,838
  • 16
  • 20
  • 1
    "the list item is copied" isn't quite right. Assignment never copies data. You could say that the list item gets the name tag `char`. Then when you do `char = 'b'` the name tag is taken away from the list item and applied to `'b'`. The list item itself is unchanged. – Matthias Apr 16 '20 at 17:44
  • Thanks for pointing this out @Matthias, edited my answer – Erich Apr 16 '20 at 17:52
0

In the second example, you are reassigning the value of char. In the for loop, char is set as the character of the string (like 'a' or something). Then later, you're saying "ok now char is 'b'".

char is not linked to strList[i], char is independent of the string you're moving through. If you wanted the second way to work, you'd have to add one more line strList[i] = char

ewhiting
  • 244
  • 1
  • 10