1

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!

Iodizer
  • 15
  • 4

1 Answers1

2

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[:]
Joel
  • 22,598
  • 6
  • 69
  • 93
  • this link that was provided in the duplicate question was what I was looking for: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables – Iodizer Dec 17 '14 at 01:26
  • For anyone else confused by this I suggest reading all of the comments in the duplicate question. Very helpful... – Iodizer Dec 17 '14 at 01:31