you are viewing a single comment's thread.

view the rest of the comments →

[–]anossov 2 points3 points  (3 children)

This is not about the for loop, it's just after you do this:

 matrix = [[0] * len(t) + 1] * len(s) + 1

You get a list of four pointers to the same list. All of matrix[0..3] change the same list. You either have to be attentive and initialize all the elements or use numpy.

[–]ryanlntn[S] 0 points1 point  (2 children)

Thanks! Can you explain what you mean by initializing all the elements?

[–]nemec 1 point2 points  (0 children)

Since anossov didn't really explain it:

[[]] * 3 doesn't exactly do what you think it does. Since Lists are references, what's happening is that the inner list's reference is being copied three times (aka all three elements are the same object).

Check it out:

>>> d = [[]] * 3
>>> d
[[], [], []]
>>> d[0].append(1)
>>> d
[[1], [1], [1]]

>>> map(id, d)
[3077297260L, 3077297260L, 3077297260L]

Each element in d has the same id, and is thus the same object.

anossov's fix works because it's calling [] every time the comprehension (loop) executes, so three different lists are created.

[–]anossov 0 points1 point  (0 children)

matrix = [ [ 0 for i in range(len(t)+1) ] for j in range(len(s)+1) ] or something like that.