I might be missing something about the intended behavior of list extend, but why does the following happen?
x = [[],[]]
y = [[]] * 2
print x # [[],[]]
print y # [[],[]]
print x == y # True
x[0].extend([1])
y[0].extend([1])
print x # [[1],[]], which is what I'd expect
print y # [[1],[1]], wtf?
I would guess that the *
operator is doing something unexpected here, though I'm not exactly sure what. It seems like something is going on under the hood that's making the original x and y (prior to calling extend) not actually be equal even though the ==
operator and repr
both would make it seem as though they were identical.
I only came across this because I wanted to pre-populate a list of empty lists of a size determined at runtime, and then realized that it wasn't working the way I imagined. I can find a better way to do the same thing, but now I'm curious as to why this didn't work. This is Python 2.5.2 BTW - I don't have a newer version installed so if this is a bug I'm not sure if it's already fixed.