Numpy Array of Sets

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Sat May 24 18:25:55 EDT 2014


On 25.05.2014 00:14, Robert Kern wrote:
> On 2014-05-24 23:05, Luis José Novoa wrote:
>> Hi All,
>>
>> Hope you're doing great. One quick question. I am defining an array of
>> sets using numpy as:
>>
>> a=array([set([])]*3)
>>

Has nothing to do with numpy, but the problem is exclusively with your 
innermost expression [set([])]*3.

>> Now, if I want to add an element to the set in, lets say, a[0], and I
>> use the .add(4) operation, which results in:
>>

with .add you are modifying the *existing* set.

>> array([set([4]), set([4]), set([4])], dtype=object)
>>
>> which I do not want. If I use the union operator
>>
>> a[0] = a[0] | set([4])
>>

here you are forming a *new* set and put it in a[0] replacing the old 
set at this position.

>> then I obtain what I want:
>>
>> array([set([4]), set([]), set([])], dtype=object)
>>
>> Can anyone explain whay this happens?
>
> Same reason why you shouldn't make a list of lists like so: [[]]*3
>
> https://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list
>

The above link explains the underlying problem.

Best,
Wolfgang



More information about the Python-list mailing list