4、 As soon as you finish learning the list, python will be half
4.1 what is a list
List, first remember that the English is list. It is a data type in python that can dynamically add and delete content, which is composed of a series of elements. To put it bluntly, a list is a container that combines multiple variables.
Many articles will find a programming concept similar to list. Generally speaking, list in Python is similar to that in other languagesarrayThe same, but for students who don’t have any programming concepts,arrayIt is also an unfamiliar concept. In fact, you can simply understand that the list in Python is a container that can put variables of any data type.
List of definitions
The format of the list definition is as follows
my_ List = [element 1, element 2, element 3...]
Every data in the list is called an element or item, and the list is used for
Package, each element is in English
,Separated, the list can be printed out directly.
my_list = ["apple", "orange", "grape", "pear"] print(my_list)
The elements in the list can be the same data type or different data types, so it is also feasible to nest the list.
my_list = [1, "orange", True, 1.0, [1, 2, 3]] print(my_list)
4.1.2 list reading
To read the list, you need to learn two nouns, one is the index and the other is the subscript. These two words have the same meaning, both of which are to accurately obtain the elements in the list. The index can be simply understood as the concept of serial number.
First of all, you should learn that the index in the list starts from 0. This concept is a little confused at the first contact, and it will be much better if you are familiar with it. Just as we count numbers from 1, suddenly we need to start counting from 0, which requires an adaptation period.
For example, look at the list just now and try to read the index of each element in Chinese.
my_list = ["apple", "orange", "grape", "pear"]
The element with index 0 is a string
apple, the element with index 1 is a string
orange, and so on.
The syntax format of list reading is as follows:
#List name [index] my_list[i]
The above contents are converted into Python code as follows:
my_list = ["apple", "orange", "grape", "pear"] Print ("the element with index 0 is:", my_list ) Print ("the element with index 1 is:", my_list ) Print ("the element with index 2 is:", my_list ) Print ("the element with index 3 is:", my_list )
When getting elements through the index, you must pay attention to that the index starts from 0. Although it is written repeatedly, it is still easy to forget Alas~
In addition to being positive, the index can also be negative. The index of the last element of the list is – 1. The code is as follows:
nums = [1,2,3,4,5,6] Print ("the last element in the list is:", Num [- 1])
In order, – 1 represents the last element, – 2 represents the penultimate item
4.1.3 list slicing
When writing a program, the operation of the list often has the following scenarios.
- Get 1 ~ 3 elements;
- Get 4 ~ 7 elements;
- Get 1st, 3rd, 5th Item element.
These contents are converted into the actual coding of the list, which is called slicing operation, which is the slicing action now presented in your brain.
The specific syntax format is as follows:
#Read list elements from index m to n-1 my_list[m:n] #Read the first n elements of the list my_list[:n] #Reads the elements of the list from m to the end my_list[m:] #Interval s, reading list elements from m to n my_list[m:n:s]
The above contents are reflected in the code as follows. This part is presented in the code as follows. Pay special attention to the values of M and n.
my_list = ["a","b","c","d","e","f"] #Output ['a ',' B ',' C '] note that the indexes of a, B and C are 0, 1 and 2 respectively print(my_list[0:3]) #Output ['b ',' C ','d', 'e'] note that the subscripts of B, C, D and E are 1, 2, 3 and 4 respectively print(my_list[1:5]) #Output ['B', 'C','d ',' e ',' f '] print(my_list[1:]) #Output ['a', 'B', 'C','d ',' e '] print(my_list[:5]) #Output ['b ','d'] from index 1 to index 3, with an interval of 1 index print(my_list[1:4:2])
List slicing is a very important knowledge point in subsequent Python learning. The core is to figure out how the index corresponds to each element in the list.
4.1.4 list related built-in functions
In Python, there are four common built-in functions related to lists, which are to obtain the maximum value max, the minimum value min, sum sum and the number of list elements len.
Maximum and minimum
The maximum and minimum values in the list can be obtained directly by using the max and min functions. Some precautions for using this function need to be understood. For details, please refer to the code:
my_list1 = ["a","b","c","d","e","f"] my_list2 = [1,2,3,4,5,6] my_list3 = ["a",1,2,3,4] #Output f print(max(my_list1)) #Output 6 print(max(my_list2)) #Error reporting print(max(my_list3))
When the above code runs, it is found that the first two lists can output the maximum value, but the third one directly reports an error, because Max and min can only be used in lists whose elements are all numbers or all strings. If there are other data types in the list or the mixture of numbers and strings, an error will be reported.
The usage of Min is exactly the same as that of Max, and I’m not trying to write code.
The sum function can obtain the sum of list elements, but it should be noted that sum cannot be used for non numeric elements, that is, the following code is wrong.
my_list1 = ["a","b","c","d","e","f"] print(sum(my_list1))
Get the number of list elements
This function is used very frequently. You need to obtain the number of list elements in many places. You can use len function. Because the code is very simple, you can test it yourself.
4.1.5 modification and deletion of list elements
For a variable of list data type, it can modify and delete elements. This is the list mentioned at the beginning of this article. It is a data type in python that can dynamically add and delete contents (this section cannot dynamically add the list for the time being, which will be explained later).
The elements of the list can be obtained and modified through the index.
my_list1 = ["a","b","c","d","e","f"] Print ("list before modification", my_list1) my_ LIST1  = "eraser" Print ("modified list", my_list1)
The deletion of list elements can be divided into two cases: one is to delete a single element and the other is to delete multiple elements. The deletion is highly related to the list slice. You can learn from the following code.
my_list1 = ["a","b","c","d","e","f"] #Delete an element by index del my_list1 print(my_list1) my_list1 = ["a","b","c","d","e","f"] #Delete list interval elements by index del my_list1[0:3] print(my_list1) my_list1 = ["a","b","c","d","e","f"] #Delete list interval elements by index del my_list1[0:3:2] print(my_list1)
The keyword used in the delete operation is
del, the key point I believe you have also found, find the element through the index, and then
Please note that the above content is to operate the elements in the list. Next, we will learn how to operate a complete list.
4.1.6 list addition, multiplication and deletion
In Python, you can add and multiply lists directly. The addition between lists can be understood as the connection of lists. The code is as follows:
my_list1 = ["a","b"] my_list2 = ["c"] my_list3 = my_list1 + my_list2 print(my_list3)
If any number of lists are directly operated with “+”, these lists will be connected to form a new large list.
The list can be multiplied by a number, which means that the previous list is repeated many times, such as the following code:
my_list1 = ["a","b"] my_list2 = ["c"] my_list3 = my_list1 * 4 #The output result is ['a ',' B ',' a ',' B ',' a ',' B ',' a ',' a ',' B '] print(my_list3)
For the above code
[a,b] * 4The result is a list
[a,b]Repeated four times.
4.2 initial knowledge of Python object-oriented
Python is an object-oriented programming language, so all data in Python are objects. For example, integers, floating-point numbers, strings and lists learned before are objects. There is no too much explanation about the concept of object-oriented (after all, it is useless to explain now. The specific part of learning object-oriented will be explained later).
We can design some for various objects
methodIn a broad sense
function, doesn’t it sound a little windy? Some methods have been built-in for some basic objects in Python. Starting from the list, we will gradually touch the built-in methods of objects.
The calling syntax format of object method is:
Object Method ()
4.2.1 method of string object
You should first know that any data in Python is an object. After declaring a string variable, the string variable is an object. If it is an object, there will be an object method. The common methods of string are:
- Lower converts a string to lowercase
- Upper converts the string to uppercase
- Title capitalizes the first letter of the string and lowercase the rest
- Rstrip removes the white space to the right of the string
- Lstrip removes the left margin of the string
- Strip removes whitespace on both sides of a string
String case description
my_str = "good moring" my_strU = my_str.upper() my_strL = my_str.lower() my_strT = my_str.title() #Capitalize print(my_strU) #Lowercase print(my_strL) #Initial capital print(my_strT)
The corresponding output results are as follows:
GOOD MORING good moring Good Moring
Removing whitespace at the beginning or end of a string is a very useful method, which is left to you. Code can refer to
4.2.1 quick access to system built-in methods
In actual development, it is difficult for us to remember all the methods of an object. For the eraser, we also need to use the manual when writing code. There are too many methods that can’t be remembered. Just remember those commonly used. How to query all the methods of an object? A built-in function is used
For example, if you want to know all the methods of a string object, you can write the following code.
my_str = "good moring" print(dir(my_str))
After running the code, you will get the following contents, of which the red box content is the method just mentioned.
For how a method is used, you can call what you learned before
helpBuilt in functions for learning. The syntax format is as follows:
Help (object. Method)
For example, get the name of a string object
my_str = "good moring" print(help(my_str.rfind))
The results are as follows. You can understand the use of rfind method by reading it a little.
Check out the list
Since we will continue to learn the list method later, we will make a simple presentation first.
my_list1 = ["a","b"] print(dir(my_list1))
The follow-up content of this blog will explain the methods of the red box. Some people will certainly care about which ones are not in the red box_ What is the beginning? They are also methods, but it’s not time to learn them.
4.3 adding and deleting list elements by
4.3.1 list additional elements
When operating the list, the following scenarios often appear. You need to add elements to the existing list. For example, there is one element in the original list, but now you want to add two. If you set it directly, you will be prompted that the index value exceeds the length of the list. Please note that this error often occurs when operating the list.
my_list = ["apple", "orange", "grape"] my_list = "pear"
The error prompt is
IndexError: list assignment index out of range, it should be noted here that you should be familiar with some common errors in the process of learning or writing code, so that you can quickly find the cause when these errors occur.
To append elements to the list, a method is built into the list object in Python. The specific format is as follows.
my_ list. Append ("new element")
For example, you can then declare an empty list and append elements to the list.
my_list =  my_list.append("pear") my_list.append("apple") my_list.append("orange") print(my_list)
Through the append method, an element will be added at the end of the list every time. With this method, the list can be extended indefinitely.
4.3.2 list insert elements
The append method is to insert elements at the end of the list. How to insert elements at any position is a new method. The name is insert. The syntax format is as follows:
my_ list. Insert (index position, "new element")
Try to insert an element at the position of index 1, index 2 and index 0. The code is as follows:
my_list = ["pear", "apple", "orange"] my_ list. Insert (0, "insert") print(my_list) my_list = ["pear", "apple", "orange"] my_ list. Insert (2, "insert") print(my_list)
Note that when the index exceeds the length of the list, it is inserted at the end by default.
4.3.3 deleting list elements
In the previous content, we have introduced a way to delete list elements through keywords
del, a problem with this method is that the deleted element is not obtained after deleting the element. The next method will solve this problem. You will be able to get the deleted value. The method is
pop, the syntax format is as follows:
item = my_list.pop() item = my_ list. Pop (index)
Note that the pop method can carry an index value and directly delete the element at the index position. If there is no default, delete the last item. variable
itemUsed to get the deleted value. Note that when deleting elements in this method, the index cannot exceed the length of the list.
my_list = ["pear", "apple", "orange"] item = my_list.pop() print(item) Print ("after deleting elements") print(my_list)
The running result of the code is:
orange After deleting an element ['pear', 'apple']
popThe method is to delete the element according to the index. You can also delete the specified element directly. The specific method is
remove, the syntax format of this method is as follows.
my_ list. Remove (element content to be deleted)
Note that after removing an element, the deleted element will not be returned. Another problem is that if the element to be deleted is not in the list, a code error will be prompted.
If there are multiple elements to be deleted in the list, only the first one will be deleted by default. If you want to delete multiple elements, you need to use the following circular knowledge.
4.4 list sorting
In addition to adding, deleting and modifying the list, it also involves sorting related contents. This operation is also very simple for the list object. You can use a fixed method.
The sort method can sort the list elements from small to large by default. Of course, it can also be modified from large to small. This method is generally used to sort the list of pure numbers or pure English characters. If the data types of elements in the list are complex, this method is not applicable, so we need to pay attention to it.
The syntax format of sort method is as follows:
Declare a list in which all elements are numbers, and then sort.
my_list = [3, 4, 1, 2, 9, 8, 7] Print ("before sorting:", my_list) my_list.sort() Print ("after sorting:", my_list)
The output results are as follows:
Before sorting: [3, 4, 1, 2, 9, 8, 7] After sorting: [1, 2, 3, 4, 7, 8, 9]
If you want to sort from big to bottom, you only need to add parameters (the concept of parameters will be learned later)
my_list = [3, 4, 1, 2, 9, 8, 7] Print ("before sorting:", my_list) my_list.sort(reverse=True) Print ("after sorting:", my_list)
I hope you can test the sorting results of English strings. You need to pay attention to sorting the English character list. It is recommended to modify all English strings to lowercase.
Note the above
sortAfter the method is sorted, the order of the elements in the original list is modified, that is, the
my_listThe order of the list. If you don’t want to modify the order of the original list and want to generate a new list, you need to use the following methods.
4.4.2 sorted sorting
Sort sorting will permanently modify the order of list elements. In many cases, it is not necessary to modify the original list. In this case, it is necessary to use the sorted function. Note that sorted is a built-in function, not a method of list objects, that is, sorted can be used for sorting many objects.
The syntax format of the sorted function is as follows:
Sorted (list to be sorted) # positive order, from small to large Sorted (list to be sorted, reverse = true) # reverse order, from large to small
This function will return a new list after use. You can receive it with a new variable. The specific code is as follows:
my_list = [3, 4, 1, 2, 9, 8, 7] Print ("before sorting:", my_list) new_list = sorted(my_list) Print ("after sorting:", my_list) Print ("after sorting:", new_list)
Note that the new variable after sorting is
new_listFor the original
my_listThe order of elements in the list has no effect.
4.5 other methods
4.5.1 list retrieval element index
The index value of the first occurrence of a content in the list can be obtained through the index method. The format is as follows:
Index value = my_ list. Index (value to be found)
Note that if the index value is not retrieved, an error will be prompted.
my_list = [3, 4, 1, 2, 9, 8, 7] ke = my_list.index(4) ke = my_list.index(10) print(ke)
4.5.2 occurrence times of list statistical elements
The count method can be used to obtain the number of occurrences of specific elements in the list. Its syntax format is as follows:
Times = my_ list. Count (value to be found)
This method also returns 0 when the value to be found is not found in the list.
my_list = [3, 4, 3, 2, 3, 8, 7] nums = my_list.count(3) print(nums)
4.5.3 converting lists to strings
All elements in the list can be combined into a string through the join method. The syntax format is as follows:
Connection string Join (list to be converted)
This method is actually a method of string object.
my_list = ["pear", "apple", "orange"] my_str = "#".join(my_list) print(my_str)
When using this method, it should be noted that all elements in the list must be strings, otherwise they will appear
expected str instance, int foundWrong.
4.5.4 additional list
The append method can append elements to a list, and extend can append a list to a list, which is equivalent to connecting the two lists.
List 1 Extend (list 2)
Note that the appended list is appended at the end of the original list by default, so the elements in the original list have changed after appending.
my_list1 = [1, 2, 3] my_list2 = [4, 5, 6] my_list1.extend(my_list2) print(my_list1)
4.6 multidimensional list
The elements in the list can be of any data type, so the nested list is also possible.
my_list = [1,2,3,[4,5,6]]
This method needs to pay attention to that when obtaining the elements in the nested list, it needs to obtain them according to the level. For example, if you want to obtain element 5, you must first obtain the fourth element in the outermost list, that is
my_list, and then get it, and then get the element with its index position of 1, that is
my_list, the specific code can be tried by yourself, or it can be nested in the inner list and loop indefinitely.
4.7 special list string
Now let’s go back and look at the string format
"abcsdasa", a string can be regarded as a list composed of characters, which is generally called a character sequence (sequential list). A string cannot be completely equivalent to a list, because a single element cannot be modified in the string.
4.7.1 string index and slicing
A string can also access an element through an index. The index is used in the same way as the list, such as the following code:
my_str = "abcdefghi" print(my_str) print(my_str) print(my_str)
List slicing can also be used for strings, which is equivalent to obtaining string substrings.
4.7.2 partial functions and methods available for Strings
List related built-in methods, such as len, Max and min, can also be used for strings. You can try the specific contents by yourself.
4.7.3 converting strings to lists
Through the built-in function list, the string can be converted into a list, that is, each character in the string can be disassembled.
my_str = "abcdefghi" print(list(my_str))
The output content is:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
4.8 summary of this blog
The list belongs to a very important data type in the basic part of Python. When writing this blog, I was also considering whether to include all the contents. As a result, I found that there are too many contents, many of which are highly related to the later generation. In this blog, I also preliminarily learned some of the simplest concepts of object-oriented.