Plopern Plopern - 1 year ago 62
Python Question

Python: Elements in a list not being changed?

I'm having issues with editing elements in a list in Python, I've got the following code:

mylist = ["one", "day", "soon"]
for x in mylist:
x = "New word"


I would expect the output to be "New Word" three times (once for each iteration) and then a list of ["New Word", "New Word", "New Word"], but instead I've been getting:

New word

New word

New word

['one', 'day', 'soon']

Question: Why is the list apparently changing, but then reverting back to its original form when printed as a whole list?

Note: I have fixed the issue with the following code, but I am still curious as to why the original method fails

mylist2 = ["a", "b", "c"]
for x in mylist2 :
mylist2[mylist2.index(x)] = "Woo"


Answer Source

The problem is that when you iterate with for x in mylist and then assign a value to x, you are creating a new variable called x and that is what you are printing. You cannot change the list in that way, only by iterating like this:

for i in range(len(mylist)):
    mylist[i] = "New word"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download