Reputation: 65
I'm taking a data structures course in Python, and a suggestion for a solution includes this code which I don't understand.
This is a sample of a dictionary:
vc_metro = {
'Richmond-Brighouse': set(['Lansdowne']),
'Lansdowne': set(['Richmond-Brighouse', 'Aberdeen'])
}
It is suggested that to remove some of the elements in the value, we use this code:
vc_metro['Lansdowne'] -= set(['Richmond-Brighouse'])
I have never seen such a structure, and using it in a basic situation such as:
my_list = [1, 2, 3, 4, 5, 6]
other_list = [1, 2]
my_list -= other_list
doesn't work. Where can I learn more about this recommended strategy?
Upvotes: 1
Views: 5471
Reputation: 114588
You can't subtract lists, but you can subtract set
objects meaningfully. Sets are hashtables, somewhat similar to dict.keys()
, which allow only one instance of an object.
The -=
operator is equivalent to the difference
method, except that it is in-place. It removes all the elements that are present in both operands from the left one.
Your simple example with sets would look like this:
>>> my_set = {1, 2, 3, 4, 5, 6}
>>> other_set = {1, 2}
>>> my_set -= other_set
>>> my_set
{3, 4, 5, 6}
Curly braces with commas but no colons are interpreted as a set object. So the direct constructor call
set(['Richmond-Brighouse'])
is equivalent to
{'Richmond-Brighouse'}
Notice that you can't do set('Richmond-Brighouse')
: that would add all the individual characters of the string to the set, since strings are iterable.
The reason to use -=
/difference
instead of remove
is that differencing only removes existing elements, and silently ignores others. The discard
method does this for a single element. Differencing allows removing multiple elements at once.
The original line vc_metro['Lansdowne'] -= set(['Richmond-Brighouse'])
could be rewritten as
vc_metro['Lansdowne'].discard('Richmond-Brighouse')
Upvotes: 7