4

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]
--------------
Jeff
  • 6,932
  • 7
  • 42
  • 72

2 Answers2

7

The lst[:] trick makes a copy of one level of list. You've got nested lists, so you may want to have a look at the services offered by the copy standard module.

In particular:

first = foo(copy.deepcopy(mylst), "first")
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

You aren't making another copy of mylist. Both times you call foo, you are passing the same object reference and modifying the same list.

TJD
  • 11,800
  • 1
  • 26
  • 34