*Memo:
- My post explains a frozenset (1).
A set can be unpacked with an assignment and for
statement, function and *
but not with **
as shown below:
v1, v2, v3 = {0, 1, 2}
print(v1, v2, v3)
# 0 1 2
v1, *v2, v3 = {0, 1, 2, 3, 4, 5}
print(v1, v2, v3) # 0 [1, 2, 3, 4] 5
print(v1, *v2, v3) # 0 1 2 3 4 5
for v1, v2, v3 in {frozenset({0, 1, 2}), frozenset({3, 4, 5})}:
print(v1, v2, v3)
# 3 4 5
# 0 1 2
for v1, *v2, v3 in {frozenset({0, 1, 2, 3, 4, 5}),
frozenset({6, 7, 8, 9, 10, 11})}:
print(v1, v2, v3)
print(v1, *v2, v3)
# 6 [7, 8, 9, 10] 11
# 6 7 8 9 10 11
# 0 [1, 2, 3, 4] 5
# 0 1 2 3 4 5
print(*{0, 1}, 2, *{3, 4, *{5}})
# 0 1 2 3 4 5
print({*{0, 1}, 2, *{3, 4, *{5}}})
# {0, 1, 2, 3, 4, 5}
def func(p1='a', p2='b', p3='c', p4='d', p5='e', p6='f'):
print(p1, p2, p3, p4, p5, p6)
func()
# a b c d e f
func(*{0, 1, 2, 3}, *{4, 5})
# 0 1 2 3 4 5
def func(p1='a', p2='b', *args):
print(p1, p2, args)
print(p1, p2, *args)
print(p1, p2, ['A', 'B', *args, 'C', 'D'])
func()
# a b ()
# a b Nothing
# a b ['A', 'B', 'C', 'D']
func(*{0, 1, 2, 3}, *{4, 5})
# 0 1 (2, 3, 4, 5)
# 0 1 2 3 4 5
# 0 1 ['A', 'B', 2, 3, 4, 5, 'C', 'D']
A set can be continuously used through multiple variables as shown below:
A = B = C = {10, 20, 30} # Equivalent
# A = {10, 20, 30}
A.update({40, 50}) # B = A
B.remove(30) # C = B
C.pop()
print(A) # {20, 40, 10}
print(B) # {20, 40, 10}
print(C) # {20, 40, 10}
The set with a frozenset can be shallow-copied and deep-copied as shown below:
<Shallow copy>:
*Memo:
-
A
andB
refer to different outer sets and the same inner frozenset. -
is
keyword can check ifA
andB
refer to the same outer set and/or inner frozenset. -
set.copy(), copy.copy() and set() can shallow-copy the set with a frozenset:
-
set.copy()
has no arguments.
-
import copy
A = {frozenset([0, 1, 2])}
B = A.copy()
B = copy.copy(A)
B = set(A)
print(A) # {frozenset({0, 1, 2})}
print(B) # {frozenset({0, 1, 2})}
print(A is B)
# False
A = A.pop()
B = B.pop()
print(A) # frozenset({0, 1, 2})
print(B) # frozenset({0, 1, 2})
print(A is B)
# True
<Deep copy>:
*Memo:
-
A
andB
refer to different outer sets and inner frozensets. - copy.deepcopy() deep-copies the set with a frozenset.
-
copy.deepcopy()
should be used because it's safe, deeply copying the set with a frozenset whileset.copy()
,copy.copy()
andset()
aren't safe, shallowly copying the set with a frozenset.
import copy
A = {frozenset([0, 1, 2])}
B = copy.deepcopy(A)
print(A) # {frozenset({0, 1, 2})}
print(B) # {frozenset({0, 1, 2})}
print(A is B)
# False
A = A.pop()
B = B.pop()
print(A) # frozenset({0, 1, 2})
print(B) # frozenset({0, 1, 2})
print(A is B)
# False
Top comments (0)