List weirdness - what the heck is going on here?
Rotwang
sg552 at hotmail.co.uk
Thu Jan 28 07:11:05 EST 2010
Owen Jacobson wrote:
> On 2010-01-27 21:06:28 -0500, Rotwang <sg552 at hotmail.co.uk> said:
>
>> 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
>
> Consider that this is equivalent to
>
> def f(self):
> x = [0]
> self.data = [x, x]
>
> self.data is now a list containing two references to the list referenced
> by x -- so changes via either of the elements of self.data will affect
> both elements. Your comprehension version creates a list containing two
> distinct list objects, so this doesn't happen.
Thanks, and likewise to everyone else who replied.
More information about the Python-list
mailing list