I am new to Python and just stumbled on adding list
to set
. Now I know the reason why this is not possible is that list
is mutable so its hashcode
(or the Python corresponding concept) will change. Reflecting on my programming in Java, I found that I have done this many times.
HashSet<ArrayList<String>> masterCollection = new HashSet<ArrayList<String>>();
ArrayList<String> a = new ArrayList<String>();
masterCollection.add(a);
a.add("Hello, World");
for(ArrayList<String> list : masterCollection) {
// do something to list
}
I did not notice any abnormal behaviors of the above code. I even used ArrayList
as keys to HashMap
and succeeded in accomplishing my task.
Therefore, I want to ask how internally Python is different in Java in this aspect and whether there are something I need to pay attention to when writing the above code.
set
should not be responsible of monitoring thehashcode
of its elements all the time and change accordingly. But I don't think there is a mechanism forArrayList
to report itshashcode
change every time its element changes. So how does it work?HashSet
(or similar hash-related construct) the results are undefined. That's why you should only put immutable things in them.set
enforces the uniqueness of the lists (any two lists in the set should NOT be identical). But, if the lists keep changing - how do you enforce that ? now take the same problem to a multithreaded environment and you got yourself into a real mess...