List weirdness - what the heck is going on here?

Arnaud Delobelle arnodel at googlemail.com
Thu Jan 28 08:21:28 CET 2010


Rotwang <sg552 at hotmail.co.uk> writes:

> Hi all, I've been trying to make a class with which to manipulate
> sound data, and have run into some behaviour I don't understand which
> I hope somebody here can explain. The class has an attribute called
> data, which is a list with two elements, one for each audio channel,
> each of which is a list containing the audio data for that channel. It
> also has various methods to write data such as sine waves and so on,
> and a method to insert data from one sound at the start of data from
> another. Schematically, the relevant bits look like this:
>
> class sound:
>     def f(self):
>         self.data = [[0]]*2
>
>     def insert(self, other):
>         for c in xrange(2):
>             self.data[c][0:0] = other.data[c]
>
> However, the insert method doesn't work properly; x.insert(y) adds two
> copies of y's data to the start of x's data, instead of one. From a
> session in IDLE:
>
>>>> x = sound()
>>>> y = sound()
>>>> x.f()
>>>> y.f()
>>>> x.data
> [[0], [0]]
>>>> x.insert(y)
>>>> x.data
> [[0, 0, 0], [0, 0, 0]]
>
> But suppose I replace the line
>
>   self.data = [[0]]*2
>
> with
>
>   self.data = [[0] for c in xrange(2)]
>
> Then it works fine:
>
>>>> x = sound()
>>>> y = sound()
>>>> x.f()
>>>> y.f()
>>>> x.data
> [[0], [0]]
>>>> x.insert(y)
>>>> x.data
> [[0, 0], [0, 0]]
>
> Can anybody tell me what's going on?

It's a FAQ!

http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list

-- 
Arnaud



More information about the Python-list mailing list