I don't know what's wrong here, I'm sure someone here can help though. I have a list mylst
(list of lists) that's being copied and passed into the method foo
. foo
iterates through the list and replaces the first element in the row with a passed in var and returns the altered list. I print the list and I see it gives me what I expect. I repeat that process again with another copy of mylst
and a different passed in var. So the two returned lists should be different; however when I check the first list again I see that it's now the second list, also mylst
has changed to that of the second list. Am I not copying the list correctly? I'm copying it with the mylst[:]
method. Also another interesting observation is that all the list IDs are different. Doesn't that mean it's a different list than the others? Here's an example of my problem.
def printer(lst):
print "--------------"
for x in lst:
print x
print "--------------\n"
def foo(lst, string):
for x in lst:
x[0] = string
print "in foo"
for x in lst:
print x
print "in foo\n"
return lst
mylst = [[1, 2, 3], [4, 5, 6]]
print "mylst", id(mylst), "\n"
first = foo(mylst[:], "first")
print "first", id(first)
printer(first) # Correct
second = foo(mylst[:], "second")
print "second", id(second)
printer(second) # Correct
print "first", id(first)
printer(first) # Wrong
print "mylst", id(mylst)
printer(mylst) # Wrong
Here's the print out on my computer
mylst 3076930092
in foo
['first', 2, 3]
['first', 5, 6]
in foo
first 3076930060
--------------
['first', 2, 3]
['first', 5, 6]
--------------
in foo
['second', 2, 3]
['second', 5, 6]
in foo
second 3076929996
--------------
['second', 2, 3]
['second', 5, 6]
--------------
first 3076930060
--------------
['second', 2, 3]
['second', 5, 6]
--------------
mylst 3076930092
--------------
['second', 2, 3]
['second', 5, 6]
--------------