*Memo:
A set cannot be read by indexing and slicing and changed by indexing, slicing and a del statement as shown below:
*Memo:
- A
del
statement cannot remove zero or more elements from a set by indexing and slicing but can remove one or more variables themselves.
A = {10, 20, 30, 40, 50, 60}
print(A[1], A[3:5])
print(A[-5], A[-3:-1])
# TypeError: 'set' object is not subscriptable
A = {10, 20, 30, 40, 50, 60}
A[1] = 'X'
A[-5] = 'X'
A[3:5] = ['Y', 'Z']
A[-3:-1] = ['Y', 'Z']
A[1], A[3:5] = 'X', ['Y', 'Z']
A[-5], A[-3:-1] = 'X', ['Y', 'Z']
# TypeError: 'set' object does not support item assignment
A = {10, 20, 30, 40, 50, 60}
del A[1], A[3:5]
del A[-5], A[-2:5]
# TypeError: 'set' object does not support item deletion
A = {10, 20, 30, 40, 50, 60}
del A
print(A)
# NameError: name 'A' is not defined
If you really want to read a set by indexing and slicing or change a set by indexing, slicing and a del
statement, use list() and set() as shown below:
A = {10, 20, 30, 40, 50, 60}
A = list(A)
print(A[1], A[3:5])
print(A[-5], A[-3:-1])
# 20 [10, 60]
A[1] = 'X'
A[-5] = 'X'
A[3:5] = ['Y', 'Z']
A[-3:-1] = ['Y', 'Z']
A[1], A[3:5] = 'X', ['Y', 'Z']
A[-5], A[-3:-1] = 'X', ['Y', 'Z']
A = set(A)
print(A)
# {'Z', 40, 50, 'Y', 30, 'X'}
A = {10, 20, 30, 40, 50, 60}
A = list(A)
del A[1], A[3:5]
# del A[-5], A[-2:5]
A = set(A)
print(A)
# {40, 50, 10}
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 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)