Posts

Showing posts with the label immutability

Python assignment in for loops (theory clarification)

Python assignment in for loops (theory clarification) I need to clarify what is going here, and what is the real reason for it: array = [0, 1, 2] for element in array: element += 1 print array #CHANGES NOTHING double_array = [[0,1], [2,3]] for element in double_array: element[0] = "Changed!" print double_array #THIS WORKS for element in double_array: element = ["Doesn't work!"] print double_array #NOPE I understand this intuitively, but I'm not sure about the theory behind this. The way I feel is that the variable name in python is this ethereal thing that immediately falls apart if you put "=" directly after it. If the variable refers to a list, you can use ".append" after it, or "[0] =" after it, and it acts like a reference in C, but if you assign something to it directly, python is immediately like, "oh you don't need this name anymore? Ok, now it just refers to this thing you assigned to it, and nothing...