*Memo:
- My post explains a tuple (1).
- My post explains a tuple (2).
- My post explains a tuple (3).
- My post explains a tuple (5).
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[0] = 'X'
v[2:6] = ['Y', 'Z']
# TypeError: 'tuple' object does not support item assignment
v = ('a', 'b', 'c', 'd', 'e', 'f')
del v[0], v[3: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[0] = 'X'
v[2:6] = ['Y', 'Z']
v = tuple(v)
print(v)
# ('X', 'b', 'Y', 'Z')
v = ('a', 'b', 'c', 'd', 'e', 'f')
v = list(v)
del v[0], v[3:5]
v = tuple(v)
print(v)
# ('b', 'c', 'd')
A tuple 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 ((0, 1, 2), (3, 4, 5)):
print(v1, v2, v3)
# 0 1 2
# 3 4 5
for v1, *v2, v3 in ((0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11)):
print(v1, v2, v3)
print(v1, *v2, v3)
# 0 [1, 2, 3, 4] 5
# 0 1 2 3 4 5
# 6 [7, 8, 9, 10] 11
# 6 7 8 9 10 11
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']
Top comments (0)