-1

I am doing a problem, like word ladder. Originally I have a string list: paths = [[A]]. Now B, C and D are all strings which have only one different letter compared to A. What I wish to do is to make

[[A]] with [B,C,D] ->  paths = [[A,B], [A,C], [A,D]]

But if I copy the [[A]] threes tames to prepare paths = [[A], [A], [A]] using paths = [paths[0]]*3, then then doing:

i=0
for word in [B,C,D]:
    newpath = paths[i]
    paths.append(newpath.append(word))
    i += 1

which shows [[A, B, C, D], [A, B, C, D], [A, B, C, D]]. It seems the same operation on each copy. Even though I used paths = [paths[0] for i in range(3)], it is still the same. How can I avoid it? What's wrong with my code?

A ton of thanks!

TripleH
  • 447
  • 7
  • 16
  • Possible duplicate of [Python list of lists, changes reflected across sublists unexpectedly](http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly) – miradulo May 22 '16 at 19:41
  • I tried the method. See I tried "paths = [paths[0] for i in range(3)]", – TripleH May 22 '16 at 19:46

1 Answers1

1

In paths = [paths[0] for i in range(3)], paths[0] is still a reference to one and the same list. You probably want paths = [paths[0].copy() for i in range(3)].

You can put the following code to pythontutor visualization to check how it works:

paths = [['A']]
paths = [paths[0] for i in range(3)]
otherpaths = [['A']]
otherpaths = [otherpaths[0].copy() for i in range(3)]
Ilya V. Schurov
  • 7,687
  • 2
  • 40
  • 78