Search code examples
pythonscoping

python reassigment of variable


I'm new to python (using 2.7.6) and I'm sure this has been asked before, but I can't find an answer anywhere. I've looked at the python scoping rules and I don't understand what is happening in the following code (which converts three hex number strings to integers)

ls=['a','b','c']
d=ls
for i in range(0,len(d)):
    d[i]=int(d[i],64)

print str(ls)

Why does the value of ls change along with the value of d?

I couldn't repeat this behavior with simple assignments. Thanks!


Solution

  • d is ls.

    Not the value assigned to d equals the value assigned to ls. The two are one and the same. This is typical Python behavior, not just for lists.

    A simple way to do what you want is

    d = ls[:]