Is 'everything' a refrence or isn't it?

Duncan Booth duncan.booth at invalid.invalid
Wed Jan 4 14:19:02 EST 2006


KraftDiner wrote:

> I was under the assumption that everything in python was a refrence...

It is, although it is better to think in terms of names and bindings.

> 
> 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.)

During execution of this code, the name 'i' is bound to 1, 2, 3 and 4. the 
list elements are bound to 1, 2, and 3. Rebinding 'i' such that instead of 
referencing 2 it now references 4 doesn't affect the fact that the second 
element of the list references 2.

> 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?

Evidently.



More information about the Python-list mailing list