*Memo:
- My post explains a tuple (1).
- My post explains a tuple (2).
- My post explains a tuple (3).
- My post explains a tuple (4).
A tuple cannot be changed by indexing, slicing and a del statement as shown below:
*Memo:
- A
del
statement cannot remove zero or more elements from a tuple by indexing and slicing but can remove one or more variables themselves.
v = ('a', 'b', 'c', 'd', 'e', 'f')
v[1] = 'X'
v[-5] = 'X'
v[3:5] = ['Y', 'Z']
v[-3:-1] = ['Y', 'Z']
v[1], v[3:5] = 'X', ['Y', 'Z']
v[-5], v[-3:-1] = 'X', ['Y', 'Z']
# TypeError: 'tuple' object does not support item assignment
v = ('a', 'b', 'c', 'd', 'e', 'f')
del v[1], v[3:5]
# del v[-5], v[-2:5]
# TypeError: 'tuple' object does not support item deletion
v = ('a', 'b', 'c', 'd', 'e', 'f')
del v
print(v)
# NameError: name 'v' is not defined
If you really want to change a tuple, use list() and tuple() as shown below:
v = ('a', 'b', 'c', 'd', 'e', 'f')
v = list(v)
v[1] = 'X'
v[-5] = 'X'
v[3:5] = ['Y', 'Z']
v[-3:-1] = ['Y', 'Z']
v[1], v[3:5] = 'X', ['Y', 'Z']
v[-5], v[-3:-1] = 'X', ['Y', 'Z']
v = tuple(v)
print(v)
# ('a', 'X', 'c', 'Y', 'Z', 'f')
v = ('a', 'b', 'c', 'd', 'e', 'f')
v = list(v)
del v[1], v[3:5]
# del v[-5], v[-2:5]
v = tuple(v)
print(v)
# ('a', 'c', 'd')
A tuple can be continuously used through multiple variables as shown below:
v1 = v2 = v3 = ('A', 'B', 'C', 'D', 'E') # Equivalent
# v1 = ('A', 'B', 'C', 'D', 'E')
print(v1) # ('A', 'B', 'C', 'D', 'E') # v2 = v1
print(v2) # ('A', 'B', 'C', 'D', 'E') # v3 = v2
print(v3) # ('A', 'B', 'C', 'D', 'E')
A tuple cannot be shallow-copied and deep-copied as shown below:
<Shallow & Deep copy>:
*Memo:
-
v1
andv2
refer to the same outer and inner tuple. -
is
keyword can check ifv1
andv2
refer to the same outer and inner tuple. -
copy.copy(),
tuple()
and slicing cannot shallow-copy a tuple. - copy.deepcopy() cannot deep-copy and even shallow-copy a tuple.
import copy
v1 = ('A', 'B', ('C', 'D'))
v2 = copy.copy(v1)
v2 = tuple(v1)
v2 = v1[:]
v2 = copy.deepcopy(v1)
print(v1) # ('A', 'B', ('C', 'D'))
print(v2) # ('A', 'B', ('C', 'D'))
print(v1 is v2, v1[2] is v2[2])
# True True
Top comments (0)