Reputation: 8109
I have two lists with numbers.
newlist = [506.5, 133.0, 11104.2]
totalcolumns = [9.2, 10024.5, 610.0, 1100.0]
I want to loop over both lists and format the numbers in the same way:
myformatlists = [newlist, totalcolumns]
for i in range(0,len(myformatlists)):
myformatlists[i] = ['{0:,}'.format(x) for x in myformatlists[i]]
myformatlists[i] = [regex.sub("\.0?$", "", x).replace(".", "_").replace(",", ".")
printing
print(str(myformatlists[i])
gives the correct new values
but
print(str(newlist))
print(str(totalcolumns))
still gives the old lists.
Why doesn't my for-loop assign the values to the listname in myformatlists[i]?
How can I assign the output of the for-loop to the list in myformatlists?
Upvotes: 1
Views: 89
Reputation: 87064
myformatlists[i] = ['{0:,}'.format(x) for x in myformatlists[i]]
rebinds myformatlists[i]
, it does not alter the original item of myformatlists
.
You can perform an inplace update of myformatlists[i]
using slice notation:
myformatlists[i][:] = ['{0:,}'.format(x) for x in myformatlists[i]]
This will mutate the original list.
But note that there is a problem with the re code where x
is not defined becaue the list comprehension is incomplete:
myformatlists[i] = [regex.sub("\.0?$", "", x).replace(".", "_").replace(",", ".")
It should be re.sub
and perhaps the rest should be:
myformatlists[i] = [re.sub("\.0?$", "", x).replace(".", "_").replace(",", ".") for x in myformatlists[i]]
Upvotes: 3