2

I need to create list1 containing another a set of lists with 8 elements. these are then appended to a second list where the last element is changed. I am a little confused as currently when I try to change the last element, it changes the last element of both lists.

Any help on this would be really appreciated:

from random import random

list1 = []
list2 = []

for x in xrange(10):

   a, b, c, d, e, f, g = [random() for i in xrange(7)]

   list1.append([x, a, b, c,  d, e, f, g])

for y in xrange(len(list1)):

   list2.append(list1[y])
   print "Index: ", y, "\tlist1: ", list1[y][7]
   print "Index: ", y, "\tlist2: ", list2[y][7]

   list2[y][7] = "Value for list2 only"

   print "Index: ", y, "\tlist1: ", list1[y][7]
   print "Index: ", y, "\tlist2: ", list2[y][7]
Sam Perry
  • 145
  • 1
  • 12
  • Other related questions: http://stackoverflow.com/questions/16774913/why-is-list-changing-with-no-reason, http://stackoverflow.com/questions/12237342/changing-an-item-in-a-list-of-lists, http://stackoverflow.com/questions/11993878/python-why-does-my-list-change-when-im-not-actually-changing-it. – Veedrac Sep 21 '14 at 06:56

1 Answers1

1

Replace:

list2.append(list1[y])

with:

list2.append(list1[y][:])

The problem with the original code is that python is not appending the data from list1[y] onto the end of list2. Rather, python is appending a pointer to list1[y]. Change the data in either place and, because it is the same data, the change appears in both places.

The solution is to use list1[y][:] which tells python to make a copy of the data.

You can see this effect more simply without the list of lists:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7]
>>> b = a
>>> b[0] = 99
>>> a
[99, 1, 2, 3, 4, 5, 6, 7]

By contrast:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7]
>>> b = a[:]
>>> b[0] = 99
>>> a
[0, 1, 2, 3, 4, 5, 6, 7]
John1024
  • 109,961
  • 14
  • 137
  • 171