Introduction to Python from zero (3) sequence

  • 2020-04-02 13:41:58
  • OfStack

The sequence sequence

A sequence is a set of sequential elements

Strictly speaking, it is a collection of objects, but since we haven't introduced the concept of "objects", let's say elements for the moment.

A sequence can contain one or more elements, or none at all.

All of the basic data types we talked about earlier can be used as elements of a sequence. The element can also be another sequence and other objects that we'll cover later.

There are two types of sequences: tuples (fixed value table; Also translated as tuples and lists


>>>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 a tuple and a list is that, once established, the individual elements of a tuple cannot be changed, while the individual elements of a list can be changed.

One sequence ACTS as an element of another sequence


>>>s3 = [1,[3,4,5]]

An empty sequence


>>>s4 = []

Element reference

The subscript of a sequence element starts at 0:


>>>print s1[0]
>>>print s2[2]
>>>print s3[1][2]

Since the elements of list can be changed, you can assign a value to one of the elements of list:


>>>s2[1] = 3.0
>>>print s2

If you do this with a tuple, you'll get an error.

So, you can see that the reference to the sequence goes through s[ < int > ] implementation, int is subscript

Other ways of referencing

Range reference: basic style [lower: upper: step size]


>>>print s1[:5]             #  From the beginning to the index 4  (subscript 5 The elements of the   Not included) 
>>>print s1[2:]             #  From the subscript 2 In the end 
>>>print s1[0:5:2]          #  From the subscript 0 The subscript 4 ( The subscript 5 Not included ) every 2 Take an element   (subscript for 0 . 2 . 4 The element) 
>>>print s1[2:0:-1]         #  From the subscript 2 The subscript 1

As you can see from the above, if the upper limit is specified in the scope reference, then the upper limit itself is not included.

Tail element reference


>>>print s1[-1]             #  The last element of the sequence 
>>>print s1[-3]             #  The third to last element of the sequence 

Similarly, if s1[0:-1], then the last element is not referenced (again, not including the upper bound element itself)

Strings are tuples

A string is a special element, so you can perform tuple related operations.


>>>str = 'abcdef'
>>>print str[2:4]

conclusion

The tuple element is immutable, and the list element is mutable

Sequence reference s[2], s[1:8:2]

A string is a tuple


Related articles: