Skip to content Skip to sidebar Skip to footer

Changing An Item In A List Of Lists

Possible Duplicate: Simple python code about double loop I'm stuck with the well known problem of changing 1 item in a list of lists. I need to use a fixed size list of list. If

Solution 1:

There is a fundamental difference in the 2 ways you defined the matrix in both code samples. In the first (line 21) when you multiply the outer list by 3 you actually multiply the references to the inner list.

Here's a parameterized example:

a = [2,2]
b = [a] * 3b => [a, a, a] => [[2,2], [2,2], [2,2]]

As you can see the numerical representation of b is what you would expect, but it actually contains 3 references to a. So if you change either of the inner lists, they all change, because they are actually the same list.

Instead of multiplication you need to clone the lists doing something like this

new_list = old_list[:]

or

new_list = list(old_list)

In the case of nested lists, this can be done using loops.

Post a Comment for "Changing An Item In A List Of Lists"