The ninth lesson of Python introductory basics--tuple

    1 Introduction

    This section on tuples is easy to understand. You have the knowledge of lists in the previous section, and you can understand them at a glance. A tuple, like a list, is a sequence. The only difference is that tuples cannot be modified. The syntax for creating a tuple is simple: if you separate some values ​​with a comma, then you automatically create a tuple.

    2. Tuples: Immutable Sequences

    Let's go straight to some simple examples:

>>> (1,2,3,4,5,6,7) #Initialize a tuple with elements
(1, 2, 3, 4, 5, 6, 7)
>>> () #empty tuple
()
>>> (1,) #Create a tuple with only one element
(1,)
>>> 3*(40+2)
126
>>> 3*(40+2,) #Note the difference between these two examples, which is a comma. A comma is a must, which is an important sign that distinguishes it from other types. 
(42, 42, 42)

       tuple function

    The function of the tuple function is basically the same as that of the list function: it takes a sequence as an argument and converts it to a tuple, and if the argument is a tuple, the argument is returned as-is.                           

>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1,2.3))
(1, 2.3)

      Basic tuple operations

    Tuples are actually not complicated. Apart from creating tuples and accessing tuple elements, there are not many other operations, which can be implemented by referring to other types of sequences.
>>> x=1,2,3
>>> x[1]
2
>>> x[0:2]
(1, 2)
    The sharding of a tuple is still a tuple, just like the sharding of a list is still a list, isn't it very simple.

    3. The meaning of tuples

    You might be thinking, we can just use a list, why use a tuple type, and where would it be used? Who will use it?

  • Tuples can be used as keys in maps -- lists can't
  • Tuples exist as return values ​​for many built-in functions and methods, which means you have to deal with tuples. As long as you don't try to modify the tuple, "processing" a tuple is, in most cases, operating on it as a list.
Well, this part of the tuple is very simple, it is basically ok to know these, the next chapter is our key chapter-dictionary, advance notice.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325776285&siteId=291194637