I am using Python 2.6 with ide and i created a list with names

names = 'mark', 'raymond', 'rachel', 'matthew', 'roger', 'judith', 'charlie', 'melissa', 'betty']

and then set names = nmls so even if I update names, nmls gets updated...

however if I do

names = deque(['raymond', 'rachel', 'matthew', 'roger', 'judith', 'charlie', 'melissa', 'betty'])

and then nmls gives the old list not the new names... how is this happening ?

Recommended Answers

All 7 Replies

In Python (and many other languages) there is a difference between changing variables and changing objects. A statement of the form myvar = new_value will change the variable myvar. Most other things that you can do with myvar (like myvar[i] = foo or myvar.append(bar)) will change the object, not the variable.

If you execute a statement of the form myvar = my_other_var, then the two variables will now refer to the same object. If you change that object, the change will be visible through both variables. However if you change one of the variables to refer to a different object, that change will not be visible to the other variable and the variables will no longer be connected in any way.

So names = deque(...) does not affect nmls because it's changing the variable, not the object.

names = deque(['raymond', 'rachel', 'matthew', 'roger', 'judith', 'charlie', 'melissa', 'betty'])

Will asign a new list to the variable names which than will no longer be pointing to the same memory address that nmls does (which it did till than by assigning names to nml : names = nmls), thus making the variable names hold a new object, not related to the object held by the nmls variable.

names = nmls
means let both point to the same block of memory, so both get updated.
names = nmls[:] note the colon
means names is now a copy (complete slice) of nmls. You can also use copy() and deepcopy() to get a copy of the list Click Here .

You can test it with id() ...

mylist = [1,3,5]
newlist = mylist

print id(mylist), id(newlist)

mylist = [2,4,6]

print id(mylist), id(newlist)

since a different value is set for mylist the id returned is different, but the new list should aslo get updated ....

Why should the newlist get updated? It's now a totally different object.

Python keeps all variable names and values in an internal dictionary:

def test():
    mylist = [1,3,5]
    newlist = mylist
    print vars()
    mylist = [2,4,6]
    print vars()

test()

'''
{'newlist': [1, 3, 5], 'mylist': [1, 3, 5]}
{'newlist': [1, 3, 5], 'mylist': [2, 4, 6]}
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.