Copy a list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Xx r3negade
    New Member
    • Apr 2008
    • 39

    Copy a list

    Consider the following code:
    Code:
    listA = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
    changeCoordinates = ((2, 3), (1, 3))
    
    for coordinateList in changeCoordinates:
    	listB = listA[:]
    	x = coordinateList[0]
    	y = coordinateList[1]
    	
    	listB[x][y] = 'foo'
    	print "list A: %s" % listA
    	print "list B: %s" % listB
    listA should never change. But it does. It works the way I expected on a one-dimensional list, but on a two-dimensional list, listA changes. How do I avoid this, and (out of curiosity) why the hell doesn't python just assign the value rather than the reference anyway?
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    Hi,
    listB is actually a separate copy of listA, but each of the sub-lists in listB is just a shallow copy of the corresponding sub-list in listA, if that makes any sense. To make a completely independent copy of listA, you will either have to use a loop like this:
    Code:
    for sub_list in listA:
        listB.append(sublist[:])
    or use the deepcopy() function of the copy module:
    Code:
    import copy
    listB = copy.deepcopy(listA)
    Hope this helps.

    Comment

    • Xx r3negade
      New Member
      • Apr 2008
      • 39

      #3
      OK thanks. And about the second part of my question...is there any logical reason for python to do this? Isn't it inconsistent for the assignment operator to assign a value to some data types and a reference to others? Just wondering why they did this.

      Comment

      • boxfish
        Recognized Expert Contributor
        • Mar 2008
        • 469

        #4
        Not sure. Seems like the only types that get copied as a reference are lists and object types. I think it would make more sense if tuples, strings, and dictionaries got copied as references too, because they can get really huge also. I wonder if there's a way to do shallow copying of those types in Python.

        Comment

        Working...