Python handles string and tuple immutability

Posted by Tracekill on Mon, 21 Feb 2022 05:19:11 +0100

We can change the contents of elements in the list by indexing, for example:

names = ['Luban 7', 'Cai Wenji', 'Zhen Ji', 'Arthur', 'King Lanling']
2names[0] = 'offspring'
3print(names)
4# Output: [descendant ',' Cai Wenji ',' Zhen Ji ',' Arthur ',' King of the orchid mausoleum ']

However, once the string is created, it cannot be changed. This attribute is similar to tuples. If you change the elements in the string through index, an error will be reported:

name = 'Luban 7'
2name[0] = 'Lu'
3print(name)
4# Error reporting: TypeError: 'str' does not support item assignment on line 2

So how can we modify the content of the string? The answer is to use string slicing and splicing to generate a new string. Take an example:

name = 'Luban 7'
2new_name = 'Lu' + name[1:]
3print(new_name)
4# Output: Luban 7

Tuples are very similar to lists. The difference is in appearance: the list is wrapped in square brackets, while the tuple is wrapped in parentheses. In essence: the elements in the list can be modified, and the elements in the tuple cannot be "added, deleted or modified".

Another subtle thing to note is that tuples with only one element are different from lists in format. The list of only one element X is written as [x], but the tuple of only one element should write more commas in parentheses: (x,).

This is because in Python, parentheses bear too many grammatical functions. They can be used to represent tuples or as parentheses in mathematical operations. (x) In this way, python will first understand it as parentheses for mathematical operations, so bare (x) is a mathematical operation expression with parentheses for Python. Let's look at the code:

single = (1,)
2print(type(single))
3# Output: < class' tuple '>

The multiple return value of a function is actually a tuple

def new_kids():
2  kid1 = 'Nuhara Shinsuke'
3  kid2 = 'Wind penetration'
4  kid3 = 'Masao Sato'
5  kid4 = 'Sakurada nini'
6  # Multiple values are juxtaposed after return and separated by English commas
7  return kid1, kid2, kid3, kid4
8
9print(new_kids())
10print(type(new_kids()))
11# Output:
12# ('nuhara Shinsuke', 'fengjianche', 'Masao Sato', 'Sakurada Nini')
13# <class 'tuple'>

With the relatively stable data structure of tuples, we are no longer afraid to change the data by hand!

If you really have to change the internal data of the yuan group, you will report an error:

students = ('Lin Daiyu', 'Jia Baoyu', 'Xue Baochai')
2
3students.append('Shi Xiangyun')
4# Error reporting: AttributeError: 'tuple' object has no attribute 'append'
5# (attribute error: tuple object has no append attribute)
6# Supplementary note: we will talk about "object" and "attribute" in later courses
7
8students[2] = 'Attack people'
9# Error reporting: TypeError: 'tuple' object does not support item assignment
10#(wrong type: tuple object does not support assigning values to its elements)
11
12del students[1]
13# Error reported: TypeError: 'tuple' object doesn't support item deletion
14# (wrong type: tuple object does not support deletion)

In addition to the above examples, other statements and methods used to add, modify or delete can not be used on tuples. However, since the query and fragmentation operations do not change the data, the two query methods of list elements and fragmentation operations are available in tuples.

students = ('Lin Daiyu', 'Jia Baoyu', 'Xue Baochai')
2
3print(students[1])
4# Output: Jia Baoyu
5
6print(students.index('Jia Baoyu'))
7# Output: 1
8
9print(students[:2])
10# Output: ('Lin Daiyu', 'Jia Baoyu')

List operators and tuples are also supported. Query whether the element is in the tuple with ; in ;; Stack the two tuples with + to generate a new element group; Use * to generate a new element group whose elements are cycled multiple times.  

students = ('Lin Daiyu', 'Jia Baoyu', 'Xue Baochai')
2
3daiyu_in = 'Lin Daiyu' in students
4print(daiyu_in)
5# Output: True
6
7students_plus = students + students
8print(students_plus)
9# Output: ('Lin Daiyu', 'Jia Baoyu', 'Xue Baochai', 'Lin Daiyu', 'Jia Baoyu', 'Xue Baochai')
10
11students_triple = students * 3
12print(students_triple)
13# Output: ('Lin Daiyu', 'Jia Baoyu', 'Xue Baochai', 'Lin Daiyu', 'Jia Baoyu', 'Xue Baochai', 'Lin Daiyu', 'Jia Baoyu', 'Xue Baochai')

What if you really have special needs and need to modify the elements in the tuple?  

Here's an idea. You can first use the # list() function to convert tuples into lists, which is equivalent to "unlocking" the data. After modifying the elements, you can use the # tuple() function to convert them back to tuples, which is equivalent to "re locking".  

students = ('Lin Daiyu', 'Jia Baoyu', 'Xue Baochai')
2
3# Use the list() function to "unlock" the data and generate a new list of the same elements
4students_list = list(students)
5
6# Modify elements in a new list
7students_list[0] = 'Miaoyu'
8
9# "Lock" the data twice
10students = tuple(students_list)
11
12print(students)
13# Output: ('Miaoyu', 'Jia Baoyu', 'Xue Baochai')

Summary: the difference between list and tuple is like movable type printing and stone tablet in our four great inventions. Both can be engraved, but each font of the former can be adjusted as needed, which is suitable for books, leaflets and other contents with more changes. The stone tablet is a complete stone slab, which cannot be changed once carved. It is suitable for important contents to be preserved for a long time.  

Topics: Python Back-end