KraftDiner wrote: > I was under the assumption that everything in python was a refrence... > > so if I code this: > lst = [1,2,3] > for i in lst: > if i==2: > i = 4 > print lst > > I though the contents of lst would be modified.. (After reading that > 'everything' is a refrence.) > so it seems that in order to do this I need to code it like: > > lst = [1,2,3] > for i in range(len(lst)): > if lst[i] == 2: > lst[i]=4 > print lst > > Have I misunderstood something? > To give a short answer: yes.
And now into the details assuming, that your misunderstanding comes from programming in C before evaluating Python: If you write i = 4 following happens: an integer literal 4 gets into the scope of Python script as an object of type integer and can be from now on reached using the identifier i . So i is in this context a _kind of_ pointer/reference to the value '4', but ... in Python sense not in C sense. if you write for i in lst: then the identifier i 'points' to values in lst, but else as in C where you can use a pointer to change the value it points to by assigning to *i or where you can use a reference to change a value it references, in Python you don't change a value of i because i is an identifier and therefore has no value in sense of C - it is only a name used to reach a value. When you write within the 'for i in lst:' loop i = 4 you just use the identifier i as a 'pointer' to another Python object as it was pointing to before. Let's consider a list. The 'identifier'(i.e. construct) lst[i] pointing to a list element behaves in Python like what you understand in C as a reference. This is the main difference between the meaning of = assignment in Python and in C and it usually results in problems with understanding it when someone has programmed C and expects from Python to be like C. The core of the trouble is probably different understanding of the word 'reference', which used in different contexts (e.g. Python and C) means different things. Therefore as Scott David Daniels says "There is a reason people talk about names and bindings." Claudio -- http://mail.python.org/mailman/listinfo/python-list