Python sequence (list and tuple) usage complete introduction

Python sequence (list and tuple) usage complete introduction

  • The so-called sequence refers to a sequence containing multiple data data structure , the sequence contains multiple data items (also known as members) arranged in order, and the members can be accessed through the index.
    Common sequence types in Python include strings, lists, and tuples. The string introduced in the previous chapter is actually a common sequence. The program to access the characters in the string through the index is the demonstration program of the sequence.
  • The sequences introduced in this section mainly refer to lists and tuples. These two types look very similar. The main difference is that tuples are immutable. Once tuples are constructed, the program cannot modify the members contained in tuples (just like the string is immutable, and the program cannot modify the character sequence contained in the string); However, the list is variable, and the program can modify the elements contained in the list.
  • In the specific programming process, if only multiple data items are saved fixedly, there is no need to modify them, and tuples should be used at this time; Instead, use lists. In addition, in some cases, programs need to use immutable objects, such as
    Python requires that the key of the dictionary must be immutable. At this time, the program can only use tuples.

In short, the relationship between list and tuple is variable and immutable.

Create lists and tuples

  • The syntax of creating lists and tuples is also somewhat similar. The difference is that square brackets are used to create lists, parentheses are used to create tuples, and the elements of tuples are listed in parentheses, which are separated by English commas.

The syntax format for creating a list is as follows:

[ele1,ele2,ele3,...]

The syntax format for creating tuples is as follows:

(ele1,ele2,ele3,...)

The following code demonstrates how to define lists and tuples in a program:

a_tuple = ('crazyit', 20, 5.6, 'fkit', -17)
print(a_tuple)
# Access the first element
print(a_tuple[0]) # crazyit
# Access the 2nd element
print(a_tuple[1]) # 20
# Access the penultimate element
print(a_tuple[-1]) # -17
# Access the penultimate element
print(a_tuple[-2]) # -fkit

List and tuple slicing

  • Similar to the string operations described earlier, lists and tuples can also use indexes to get the middle segment. This usage is called slice. The complete syntax format of slice is as follows:
[start : end : step]
  • In the above syntax, both start and end index values can use positive or negative numbers, where negative numbers mean to start from the reciprocal. This syntax represents all elements from the element of the start index (included) to the element of the end index (not included), which is similar to the Convention of all programming languages.

Step represents the step size, so it makes no sense to use a negative number in step.

The following code demonstrates the use of start and end to obtain the middle segment of tuples:

a_tuple = ('crazyit', 20, 5.6, 'fkit', -17)
# Access all elements from the second to the penultimate (excluding)
print(a_tuple[1: 3]) # (20, 5.6)
# Access all elements from penultimate to penultimate (not included)
print(a_tuple[-3: -1]) # (5.6, 'fkit')
# Access all elements from the second to the penultimate (not included)
print(a_tuple[1: -2]) # (20, 5.6)
# Access all elements from the penultimate to the fifth (excluding)
print(a_tuple[-3: 4]) # (5.6, 'fkit')

If the step parameter is specified, the element can be retrieved at an interval of step elements. For example, the following code:

b_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# Access all elements from 3rd to 9th (not included) with interval of 2
print(b_tuple[2: 8: 2]) # (3, 5, 7)
# Access all elements from 3rd to 9th (not included) with an interval of 3
print(b_tuple[2: 8: 3]) # (3, 6)
# Access all elements from the third to the penultimate (not included) with an interval of 3
print(b_tuple[2: -2: 2]) # (3, 5, 7)

addition

  • Lists and tuples support addition. The sum of addition is the sum of the elements contained in two lists or tuples.
  • It should be noted that the list can only be added to the list; Tuples can only be added to tuples; Tuples cannot be added directly to the list.

The following code demonstrates the addition of tuples and lists:

a_tuple = ('crazyit' , 20, -1.2)
b_tuple = (127, 'crazyit', 'fkit', 3.33)
# Calculate tuple addition
sum_tuple = a_tuple + b_tuple
print(sum_tuple) # ('crazyit', 20, -1.2, 127, 'crazyit', 'fkit', 3.33)
print(a_tuple) # a_tuple hasn't changed
print(b_tuple) # b_tuple hasn't changed
# Add two tuples
print(a_tuple + (-20 , -30)) # ('crazyit', 20, -1.2, -20, -30)
# The following code reports an error: tuples and lists cannot be added directly
#print(a_tuple + [-20 , -30])
a_list = [20, 30, 50, 100]
b_list = ['a', 'b', 'c']
# Calculation list addition
sum_list = a_list + b_list
print(sum_list) # [20, 30, 50, 100, 'a', 'b', 'c']
print(a_list + ['fkit']) # [20, 30, 50, 100, 'fkit']

multiplication

  • Lists and tuples can perform multiplication with integers. The meaning of list and tuple multiplication is to repeat the elements they contain N times (N is the multiple multiplied).

The following code demonstrates the multiplication of lists and tuples:

a_tuple = ('crazyit' , 20)
# Perform multiplication
mul_tuple = a_tuple * 3
print(mul_tuple) # ('crazyit', 20, 'crazyit', 20, 'crazyit', 20)
a_list = [30, 'Python', 2]
mul_list = a_list * 3
print(mul_list) # [30, 'Python', 2, 30, 'Python', 2, 30, 'Python', 2]
  • Of course, you can also add and multiply lists and tuples at the same time. For example, translate the date entered by the user into English, that is, add the suffix "No." in English. For 1, 2 and 3, the suffixes of "No. 1" in English are represented by st, nd and rd respectively, while others are represented by th.

For this purpose, the following code can be used to complete the conversion:

# At the same time, addition and multiplication are used for tuples
order_endings = ('st', 'nd', 'rd')\
    + ('th',) * 17 + ('st', 'nd', 'rd')\
    + ('th',) * 7 + ('st',)
# You will see st, nd, rd, 17 th, St, nd, rd, 7 th, St
print(order_endings)
day = input("Enter date(1-31): ")
# Convert string to integer
day_int = int(day)
print(day + order_endings[day_int - 1])
  • In this program, multiplication is used for ('th ',) tuples at the same time, and then the results obtained by multiplication are connected by addition to finally obtain a tuple with 31 elements in total.
Some readers may be right ('th',) Curious about this way of writing, there is clearly only one element here. Why not omit the comma?
that is because ('th') It's just a string with parentheses, not a tuple, that is,('th') and 'th' Is the same.
In order to represent a tuple with only one element, you must add an English comma after the unique tuple element.
  • Run the above program and you can see the following results:
Enter date(1-31): 27
27th

From the above running results, it can be seen that when the user inputs 27, the program adds the suffix "th" to 27 through the tuple.

in operator

The in operator is used to determine whether a list or tuple contains an element. For example, the following code:

a_tuple = ('crazyit' , 20, -1.2)
print(20 in a_tuple) # True
print(1.2 in a_tuple) # False
print('fkit' not in a_tuple) # True

Length, maximum and minimum

  • Python provides built-in ten(), max(), min() global functions to obtain the length, maximum and minimum values of tuples or lists.
  • Since max() and min() need to compare the size of tuples and elements in the list, the program requires that they be passed to max(), min()
    The tuple of the function and the elements of the list must be of the same type and can be compared in size.

For example, the following code:

# Elements are tuples of values
a_tuple = (20, 10, -2, 15.2, 102, 50)
# Calculate maximum
print(max(a_tuple)) # 102
# Calculate minimum
print(min(a_tuple)) # -2
# Calculation length
print(len(a_tuple)) # 6
# Elements are lists of strings
b_list = ['crazyit', 'fkit', 'Python', 'Kotlin']
# Calculate the maximum value (compare the ASCII code value of each character in turn, first compare the first character,
# If the same, continue to compare the second character, and so on)
print(max(b_list)) # fkit (ASCII code of 26 lowercase letters is 97 ~ 122)
# Calculate minimum
print(min(b_list)) # Kotlin (ASCII code of 26 capital letters is 65 ~ 90)
# Calculation length
print(len(b_list)) # 4

In the above code, first use three functions to process tuples whose elements are numerical values. You can see that the program obtains the maximum and minimum values of tuples.
The latter half of the program uses three functions to process the list whose elements are universal character strings. You can also see that the program obtains the maximum and minimum values of the list, which shows that Python's string can also be compared in size, that is, python compares the size of the string according to the corresponding code of each character in the string.

Sequence packet and sequence unpacking

  • Python also provides the functions of sequence packaging and Sequence Unpacking. In short, python allows the following two assignment methods:
  1. When the program assigns multiple values to a variable, Python will automatically encapsulate multiple values into meta groups. This function is called sequential packet.
  2. The program allows the sequence (tuple or list, etc.) to be directly assigned to multiple variables. At this time, each element of the sequence will be assigned to each variable in turn (the number of elements in the sequence and the number of variables are required to be equal). This function is called sequence unpacking.

The following code demonstrates the functions of sequence packet and sequence unpacking:

# Sequence packet: encapsulate 10, 20 and 30 into tuples and assign them to vals
vals = 10, 20, 30
print(vals) # (10, 20, 30)
print(type(vals)) # <class 'tuple'>
print(vals[1]) # 20
a_tuple = tuple(range(1, 10, 2))
# Unpacking sequence: a_ The elements of tuple tuple are assigned to variables a, b, c, d and e in turn
a, b, c, d, e = a_tuple
print(a, b, c, d, e) # 1 3 5 7 9
a_list = ['fkit', 'crazyit']
# Unpacking sequence: a_ Each element of the list sequence is assigned to a in turn_ str,b_str variable
a_str, b_str = a_list
print(a_str, b_str) # fkit crazyit

If the sequence packet and sequence unpacking mechanism are used in the assignment at the same time, the assignment operator can support assigning multiple values to multiple variables at the same time. For example, the following code:

# Assign 10, 20 and 30 to x, y and z in turn
x, y, z = 10, 20, 30
print(x, y, z) # 10 20 30

The above code is actually equivalent to the following execution process:

#Execute sequence packet first
xyz = 10,20,30
#Then perform sequence unpacking
x,y,z = xyz

This syntax can also be used to exchange the values of variables, such as the following code:

# Assign y, z and X to x, y and z in turn
x, y, z = y, z, x
print(x, y, z) # 20 30 10

When unpacking the sequence, you can only solve some variables, and the rest are still saved with list variables. In order to use this unpacking method, Python allows "*" to be added before the assigned variable on the left, so the variable represents a list and can hold multiple collection elements. For example, the following procedure:

# First and second save the first two elements, and the rest list contains the remaining elements
first, second, *rest = range(10)
print(first) # 0
print(second) # 1
print(rest) # [2, 3, 4, 5, 6, 7, 8, 9]
# Last saves the last element, and begin saves the remaining elements
*begin, last = range(10)
print(begin) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(last) # 9
# First saves the first element, last saves the last element, and middle saves the remaining elements in the middle
first, *middle, last = range(10)
print(first) # 0
print(middle) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
print(last) # 9

Keywords: Python list

Added by dnamroud on Sun, 30 Jan 2022 17:47:32 +0200