This article describes the sequence details of the basic python tutorial. The sequence in this article includes tuple, list, and other data types. For more information, see
Sequence
Sequence is a set of ordered elements.
(Strictly speaking, it is a collection of objects, but we have not introduced the concept of "object", so we will talk about elements for the moment)
A sequence can contain one or more elements, or contain no elements.
The basic data types we mentioned earlier can all be used as sequence elements. The element can also be another sequence and other objects we will introduce later.
There are two sequences: tuple (value table; also translated as tuples) and list (table)
The Code is as follows:
>>> S1 = (2, 1.3, 'love', 5.6, 9, 12, False) # s1 is a tuple
>>> S2 = [True, 5, 'smile '] # s2 is a list
>>> Print s1, type (s1)
>>> Print s2, type (s2)
The main difference between tuple and list is that, once created, each element of tuple cannot be changed, and each element of list can be changed.
Elements of a sequence as another sequence
The Code is as follows:
>>> S3 = [1, [3, 4, 5]
Empty Sequence
The Code is as follows:
>>> S4 = []
Element reference
The subscript of the sequence element starts from 0:
The Code is as follows:
>>> Print s1 [0]
>>> Print s2 [2]
>>> Print s3 [1] [2]
Since the list element can be changed, you can assign a value to an element in the list:
The Code is as follows:
>>> S2 [1] = 3.0
>>> Print s2
If you perform this operation on tuple, an error is returned.
Therefore, we can see that the reference of the sequence passes through s [ ] Implementation, int Is subscript
Other reference methods
Range reference: basic style [lower limit: Upper Limit: Step Size]
The Code is as follows:
>>> Print s1 [: 5] # From start to subscript 4 (Elements of subscript 5 are not included)
>>> Print s1 [2:] # From subscript 2 to the end
>>> Print s1 [] # From subscript 0 to subscript 4 (subscript 5 is not included), take an element every 2 (subscript is 0, 2, 4)
>>> Print s1 [2: 0:-1] # From subscript 2 to subscript 1
As you can see from the above, if the upper limit is specified during range reference, this upper limit is not included in itself.
Tail element reference
The Code is as follows:
>>> Print s1 [-1] # the last element of the sequence
>>> Print s1 [-3] # The last and third elements of the sequence
Similarly, if s1 [0:-1], the last element will not be referenced (again, excluding the upper limit element itself)
String is a tuples
A string is a special element, so you can perform operations on tuples.
The Code is as follows:
>>> Str = 'abcdef'
>>> Print str [2: 4]
Summary
The tuple element is unchangeable, And the list element is variable.
Reference of a sequence s [2], s []
A string is a tuple.