Skip to content Skip to sidebar Skip to footer

Understanding Lists Of Lists

Possible Duplicate: Unexpected feature in a Python list of lists Python list confusion Consider the following code: a = [[]] * 3 a[1].append('foo') I would expect the value of

Solution 1:

Lists in Python are objects, this means when you assign a list to another variable, changing either will change the actual list, for example

a = []
b = a
b.append("hi")
print a
// a is now ["hi"]

When you do the assignment

a = [[]] * 3

It's the same as saying

inner_list = []
outer_list = [inner_list, inner_list, inner_list]

In other words, all the inner lists are the same object. Not different objects as you think.

To get the effect you want, you should do:

outer_list = []
for i in range(0, 3):
    outer_list.append([])

Which creates a 3 inner lists objects and puts the into the outer object.


Solution 2:

I think you'll find what is happening is that what python is doing is creating:

outer_list = []
inner_list = []
outer_list = [inner_list,inner_list,inner_list]

or to explain it more clearly, outer_list and inner list are created once, and then inner_list is copied * 3 into outer_list, which means all 3 lists in the outer_list are actually a reference to the same inner_list copied 3 times.


Post a Comment for "Understanding Lists Of Lists"