Tuple in Python (5) – DEV Community


Buy Me a Coffee

*Memo:

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
Enter fullscreen mode

Exit fullscreen mode

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
Enter fullscreen mode

Exit fullscreen mode

v = ('a', 'b', 'c', 'd', 'e', 'f')

del v

print(v)
# NameError: name 'v' is not defined
Enter fullscreen mode

Exit fullscreen mode

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')
Enter fullscreen mode

Exit fullscreen mode

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')
Enter fullscreen mode

Exit fullscreen mode

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')
Enter fullscreen mode

Exit fullscreen mode

A tuple cannot be shallow-copied and deep-copied as shown below:



<Shallow & Deep copy>:

*Memo:

  • v1 and v2 refer to the same outer and inner tuple.
  • is keyword can check if v1 and v2 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
Enter fullscreen mode

Exit fullscreen mode



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *