Add a value to an element in a list of sets

Posted by Kapelson on Stack Overflow See other posts from Stack Overflow or by Kapelson
Published on 2010-04-28T02:13:03Z Indexed on 2010/04/28 2:23 UTC
Read the original article Hit count: 232

Filed under:
|

Hello. I'm using python, and I have a list of sets, constructed like this:

list = [set([])]*n

...where n is the number of sets I want in the list. I want to add a value to a specific set in the list. Say, the second set. I tried

list[1].add(value)

But this instead adds the value to each set in the list. This behaviour is pretty non-intuitive to me. Through further tests, I think I've found the problem: the list apparently contains 10 instances of the same set, or ten pointers to the same set, or something. Constructing the list through repeated calls of

list.append(set([]))

allowed me to use the syntax above to add elements to single sets. So my question is this: what exactly is going on in my first list-construction technique? It is clear I don't understand the syntax so well. Also, is there a better way to intialize an n-element list? I've been using this syntax for a while and this is my first problem with it.

© Stack Overflow or respective owner

Related posts about python

Related posts about mystery