"Learning Python with You Hand in Hand" 21-Tuples

In "Learning Python with You Hand in Hand" 20-Lists , we learned the definition of lists and various operation methods of lists. The tuple we are going to learn today can be regarded as a list that cannot be modified. The so-called can’t be modified means that you can’t add, delete, or modify like a list, and the slice and index methods for checking, as well as some functions and methods are very similar to the list, so today’s content is easier to understand. Come on.

1. Definition of tuple

Tuple is also a commonly used data structure in Python. It is a set of data sequences enclosed in parentheses. Like lists, the elements in tuples can be numbers, Booleans, strings, lists, variables, and other data types, or they can be lists or tuples that include the above elements, forming multiple levels of nesting. At the same time, the printed result of the tuple is also a tuple enclosed in parentheses. 

In [1]: tup1 = (1, 'a', [1, 'a'])    # 元组元素是数字、字符串、列表
        tup1
Out[1]: (1, 'a', [1, 'a'])
​
In [2]: tup2 = (1, 'a', [1, 'a'], tup1)   # 元组元素是数字、字符串、列表和变量,同时变量又是一个元组,形成嵌套
        tup2
Out[2]: (1, 'a', (1, 'a'), [1, 'a'])
​
In [3]: tup3 = ()   # 与定义空列表的方法类似,也可以定义空元组
        tup3
Out[3]: ()

With the basis of learning lists, the definition of tuples is easy to understand, but there is one thing that needs everyone's attention. First, let's look at a Liezi.

In [4]: tup4 = (1)
        tup4
Out[4]: 1

At first glance, everyone thinks that there may be no problem, but please note that the output is a number, not a tuple. This is because the identifier () of a tuple is the same as the parentheses in the mathematical symbol, so when the tuple has only one element, the program will first recognize () as a mathematical symbol rather than an identifier of a tuple. If you want to represent a tuple with only one element, you need to add a "," sign after the element, and the program will recognize it as a tuple.

In [5]: tup5 = (1,)
        tup5
Out[5]: (1,)

Here is a more convenient way to define tuples, that is, when defining tuples, you don’t need to add (), just write the elements of the tuple separated by commas, including defining tuples with only one element. The time is also applicable, but the definition of empty tuples should still be retained ().

In [6]: tup6 = 1, 'a', [1, 'a']
        tup6
Out[6]: (1, 'a', [1, 'a'])
​
In [7]: tup7 = 1,
        tup7
Out[7]: (1,)

2. Slicing and indexing of tuples

The method of tuple slicing and indexing is exactly the same as that of lists, and even our example can be completely used in "Learning Python with You" 20- the example of slicing and indexing in the list, just change the brackets [] of the list to yuan The parentheses () of the group will do. I won’t list them here anymore, please follow the official account to reply to the keyword "hand 20", download the sample file, and try it in Jupyter Notebook.

So far, the methods of slicing and indexing have been applied to strings, lists, and tuples. As mentioned before, the slicing and indexing methods are also relatively high-level rules in Python, so they will be applied to different data structures. Even when we introduce data analysis libraries Numpy and Pandas later, the more complex one-dimensional array Serise and the multi-dimensional array ndarray will use the same indexing and slicing methods. Therefore, I sincerely hope that everyone can clarify the methods and principles of slicing and indexing.

You can read "Learning Python with You Hand in Hand" 7-Indexing of Strings and "Learning Python with You Hand in Hand" 8-Slicing Strings. The methods of string slicing and indexing are introduced very well. clear. These methods are also applicable to lists, tuples, and many data types that can be sliced ​​and indexed later.

3. Modification of tuples

Seeing the title, will everyone find it a bit weird. It said that tuples cannot be modified at the beginning. Why should we introduce the modification of tuples?

If you have this idea, it is completely correct, because the elements of a tuple can neither be added, nor modified, nor deleted, just like the following example.

In [8]: tup8 = (1, 'a', [2, 'b'], True, (1, 2))
        tup8[2] = 'c'
Out[8]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-8-e82c6ece0e57> in <module>
              1 tup8 = (1, 'a', [2, 'b'], True, (1, 2))
        ----> 2 tup8[2] = 'c'
                
        TypeError: 'tuple' object does not support item assignment
        
In [9]: tup8.append(3)   # extend方法大家也可以试一下
Out[9]: ---------------------------------------------------------------------------
        AttributeError                            Traceback (most recent call last)
        <ipython-input-9-3c81a69e7b35> in <module>
        ----> 1 tup8.append(3)   # extend方法大家也可以试一下
        
        AttributeError: 'tuple' object has no attribute 'append'

Deletion It should be explained here that the term "cannot delete" means that a single or partial element in a tuple cannot be deleted, but the entire tuple can be deleted.

In [10]: tup8.remove(1)   # 不能删除单独的元素
Out[10]: ---------------------------------------------------------------------------
         AttributeError                            Traceback (most recent call last)
         <ipython-input-10-980a7164a12b> in <module>
         ----> 1 tup8.remove(1)   # 不能删除单独的元素
                
         AttributeError: 'tuple' object has no attribute 'remove'
         
In [11]: del tup8[1:2]   # 也不能删除部分元素
Out[11]: ---------------------------------------------------------------------------
         TypeError                                 Traceback (most recent call last)
         <ipython-input-11-af48f07d8ff8> in <module>
         ----> 1 del tup8[1:2]   # 也不能删除部分元素
                
         TypeError: 'tuple' object does not support item deletion
​
In [12]: del tup8   # 但可以删除整个元组
         tup8
Out[12]: ---------------------------------------------------------------------------
         NameError                                 Traceback (most recent call last)
         <ipython-input-12-051c53383cee> in <module>
               1 del tup8   # 但可以删除整个元组
         ----> 2 tup8
                
         NameError: name 'tup8' is not defined

But strictly speaking, the so-called cannot be modified means that the value or memory address of the tuple element cannot be modified, but the object of the address mapping itself can be modified. In other words, although the elements of a tuple cannot be modified, if the element of the tuple itself is changeable, then it can be modified within the element. What does this mean, let us see through an example.

In [13]: tup8 = (1, 'a', [2, 'b'], True, (1, 2))
         tup8[2][1] = 'c'
         tup8
Out[13]: (1, 'a', [2, 'c'], True, (1, 2))

In the example of In[8] above, we see that modifying the list of tup8[2], which is [2,'b'], will not work. This is because [2,'b'] is a tuple of tuples, and its memory address is determined and cannot be modified. But in the example of In[13] above, we did not modify the tuple element, that is, the memory address of this list, but modified the object mapped by this address. It is as if the list in the tuple is a bag, as long as the bag does not change, the tuple does not matter how the contents of the bag change.

This is a situation in which tuples can be "modified", and it is stated to let everyone understand this possibility, but it is still necessary to keep in mind that tuples cannot be "modified".

4. Operation of tuples

The calculation method of tuples is also the same as that of lists. Continue to use the example from the previous article to look at several calculation methods of tuples.

In [14]: (1, 2, 3) + (4, 5, 6)
Out[14]: (1, 2, 3, 4, 5, 6)
​
In [15]: (1, 2, 3) * 3
Out[15]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
​
In [16]: (1, 2, 3) == (1, 2, 3)
Out[16]: True
​
In [17]: (1, 2, 3) != (1, 2, 3)
Out[17]: False
​
In [18]: (2, 2, 3) > (1, 2, 2, 4) 
Out[18]: True
​
In [19]: 1 in (1, 2, 3)
Out[19]: True
​
In [20]: 1 not in (1, 2, 3)
Out[20]: False
​
In [21]: (1, 2, 3) is (1, 2, 3)
Out[21]: True

5. Methods and functions of tuples

Because the elements of tuples cannot be modified, the methods and functions involved in tuples are very limited, and they are all the same as lists. Therefore, only a few commonly used tuple methods and functions are listed here.

In [22]: tup9 = (1, 1, 2, 3, 4, 5, 6)
​
In [23]: len(tup9)
Out[23]: 7
​
In [24]: max(tup9)
Out[24]: 6
​
In [25]: min(tup9)
Out[25]: 1
​
In [26]: tup9.count(1)
Out[26]: 2
​
In [27]: tup9.index(3)
Out[27]: 3

In addition, there is a set of functions that convert lists and elements to each other, which is similar to the functions int(), float(), and str() that convert between integers, strings, and floating points.

In [28]: list(tup9)
Out[28]: [1, 1, 2, 3, 4, 5, 6]
​
In [29]: lst = [1, 1, 2, 3, 4, 5, 6]
         tuple(lst)
Out[29]: (1, 1, 2, 3, 4, 5, 6)

In fact, the tuple() function includes the list() function, which is not only the mutual transformation shown in the above example, but more accurately, these two functions can transform any data sequence that can be iterated into elements. Group or list. "Iteration" is the concept we focused on in "Learning Python with You Hand in Hand" 18-Loop Statement for . If you are not clear, you can click on the link above to view.

Because we said that strings can also be iterated, so tuple() and list() can convert strings into tuples or lists, and each character in the string is a tuple or list. element. However, the str() function cannot reversely convert a tuple or list of characters into the previous string. For the specific form, we will see the following example.

In [30]: a = 'Python'
​
In [31]: tuple(a)
Out[31]: ('P', 'y', 't', 'h', 'o', 'n')
​
In [32]: list(a)
Out[32]: ['P', 'y', 't', 'h', 'o', 'n']
​
In [33]: str(tuple(a))   # 元组包括()成为一个字符串
Out[33]: "('P', 'y', 't', 'h', 'o', 'n')"
​
In [34]: str(list(a))   # 列表包括[]成为一个字符串
Out[34]: "['P', 'y', 't', 'h', 'o', 'n']"

6. The role of tuples

As mentioned above, a lot of tuples do not work either (additions, deletions, and modifications are not allowed), nor do they (there are no functions and methods available). But are tuples really "not good"? Of course not, and not only is it not "not possible", it is very useful, especially its feature that it cannot be modified, like a natural "code protector", which can make the code we write more secure and stable, and not easily modified. Therefore, when applying some sequences that do not need to be modified, you should prefer tuples as the data type of this sequence, rather than lists.

7. Unpacking of tuples

After talking about the role of tuples and rehabilitating them, let's take a look at a very important application of tuples-unpacking.

We introduced "assignment" a long time ago, which is to assign the value on the right side of the equal sign to the variable on the left side of the equal sign. At that time we introduced the assignment of a value to another variable. If you want to assign multiple variables, you need multiple statements to achieve. But with the unpacking function of tuples, we can assign values ​​to multiple variables at the same time through a statement, and there is no limit to the data type.

In [35]: a, b, c, d, e = 1, 'a', [2, 'b'], True, (1, 2)   # 这是介绍元组定义时介绍的不加()定义元组的方法,在给多个变量赋值时,这种形式也更直观
         print(a, b, c, d, e)
Out[35]: 1 a [2, 'b'] True (1, 2)

If you use the special syntax format of *rest, you can also achieve unpacking of any length. Of course, the name rest has no special meaning. Many Python programmers prefer to use *_ to represent unwanted variables, but note that the final result is a list.

In [36]: tup = 1, 2, 3, 4, 5
         a, b, *_ = tup
         
In [37]: a, b   # 相当于不加()的给元组的定义,所以输出结果是元组
Out[37]: (1, 2)
​
In [38]: _
Out[38]: [3, 4, 5]

The first application of "unpacking" is to traverse a sequence of tuples or lists:

In [39]: seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
         for a, b, c in seq:
             print("a={}, b={}, c={}".format(a, b, c))
Out[39]: a=1, b=2, c=3
         a=4, b=5, c=6
         a=7, b=8, c=9

The second application of "unpacking" is to return multiple values ​​from a function. This will be explained in detail when we talk about custom functions.

The above is the explanation of Python tuples. Although from the current point of view, there are not many opportunities for us to apply tuples, when you write programs later, you can consciously use tuples to replace some of the scenes of using lists in the past. For example, you can use tuples instead of lists in the iterator of a for loop.

The next article will introduce you to a very important data type-dictionary. The data structure and display form of the dictionary are different from the lists and tuples we learned before, so it brings us more freedom and possibilities of data manipulation, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesuo Python" official account, read the other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

"Learning Python with You Hand in Hand" 20-List

For Fans: Follow the "also said Python" public account, reply "Hand 21", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/100895017