Here’s what I have:
import csv
a=8
print a
mylist = [a,'2','3']
myfile = open("myfile.csv", "wb") # csv files should always be opened in binary mode
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
a = a + 1
print a
wr.writerow(mylist)
The result of the prints are 8 and 9, just as I would expect. When I open the file I created I have the result:
"8","2","3"
"8","2","3"
The top row is what I would expect, but the second row starts with "8" rather than "9". I understand I can work around this by inserting mylist = [a,'2','3'] again after I redefine the variable, but would someone mind explaining to me why I have to reinsert the list line or why the variable isn’t automatically updated in the list? Is there another approach I can use to avoid having to reinsert the list line each time I want to update a variable?
It is the line:
in which you reassigned
ato a new integer, which is not connected to its previous value.Anyway, integers are immutable variables and you cannot do anything else with it than reassign.
As @thg435 comments, list operation
some_list = some_list + [5]would have the same effect. However, lists are mutable objects and you can usesome_list.append(5), which would modify the list and reflect its changes into the csv file.If you work with mutable objects (list, dict), you can modify their values: