This lesson is from the Real Python video course by James Uejio.
Augmented Assignment (Frozen Sets)
00:00 Besides frozen sets being immutable and regular sets being mutable, there’s also another difference. Augmented assignment works differently for normal sets and frozen sets.
00:10
You would think augmented assignment would not work for frozen sets because it mutates regular sets, but it actually does work. Here we see intersection update (&=
) and difference update (-=
) and symmetric difference update (^=
). These all work differently for frozen sets.
00:25
These are actually the same as their expanded out counterparts. So x &= {1}
is actually the same as x = x & {1}
.
00:37
So, these are actually the same for frozen sets and they’re not the same for regular sets. Here’s our side-by-side comparison. We have x = frozenset({1})
, y = x
, so now they’re pointing to the same frozenset
.
00:52
We use the augmented assignment (|=
) to union update x
. We print out x
, it’s the frozenset({1, 2})
. But when we print out y
, it’s actually still the frozenset({1})
.
01:03
So this reassigned x
. Versus y = x
, x = x | {2}
. This reassigned x
to be a new frozenset({1, 2})
, and y
is still frozenset({1})
.
01:18 Something to be careful with when using frozen sets is that you can use this augmented assignment, but you are not mutating it.
You must own this product to join the conversation.