#Raise your hands and learn Python # list. Once you finish learning python, you will learn half of it


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"]

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]]

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 stringapple, the element with index 1 is a stringorange, and so on.

The syntax format of list reading is as follows:

#List name [index]

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 [0])
Print ("the element with index 1 is:", my_list [1])
Print ("the element with index 2 is:", my_list [2])
Print ("the element with index 3 is:", my_list [3])

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
#Read the first n elements of the list
#Reads the elements of the list from m to the end
#Interval s, reading list elements from m to n

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
#Output ['b ',' C ','d', 'e'] note that the subscripts of B, C, D and E are 1, 2, 3 and 4 respectively
#Output ['B', 'C','d ',' e ',' f ']
#Output ['a', 'B', 'C','d ',' e ']
#Output ['b ','d'] from index 1 to index 3, with an interval of 1 index

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
#Output 6
#Error reporting

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"]

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 [4] = "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[0]

my_list1 = ["a","b","c","d","e","f"]
#Delete list interval elements by index
del my_list1[0:3]

my_list1 = ["a","b","c","d","e","f"]
#Delete list interval elements by index
del my_list1[0:3:2]

The keyword used in the delete operation isdel, the key point I believe you have also found, find the element through the index, and thendelDelete element.

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

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 ']

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 objectsmethodthesemethodIn a broad sensefunction, 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:

  1. Lower converts a string to lowercase
  2. Upper converts the string to uppercase
  3. Title capitalizes the first letter of the string and lowercase the rest
  4. Rstrip removes the white space to the right of the string
  5. Lstrip removes the left margin of the string
  6. 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()

#Initial capital

The corresponding output results are as follows:

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 tomy_str.strip()

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 useddir
For example, if you want to know all the methods of a string object, you can write the following code.

my_str = "good moring"

After running the code, you will get the following contents, of which the red box content is the method just mentioned.

#Raise your hands and learn Python # list. Once you finish learning python, you will learn half of it

For how a method is used, you can call what you learned beforehelpBuilt in functions for learning. The syntax format is as follows:

Help (object. Method)

For example, get the name of a string objectrfindmethod.

my_str = "good moring"


The results are as follows. You can understand the use of rfind method by reading it a little.

#Raise your hands and learn Python # list. Once you finish learning python, you will learn half of it

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"]

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.

#Raise your hands and learn Python # list. Once you finish learning python, you will learn half of it

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[3] = "pear"

The error prompt isIndexError: 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 = []


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")
my_list = ["pear", "apple", "orange"]
my_ list. Insert (2, "insert")

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 keywordsdel, 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 ispop, 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. variableitemUsed 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 ("after deleting elements")

The running result of the code is:

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 isremove, 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.

4.4.1 sort

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)

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)reverse=TrueJust.

my_list = [3, 4, 1, 2, 9, 8, 7]
Print ("before sorting:", my_list)

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 abovesortAfter the method is sorted, the order of the elements in the original list is modified, that is, themy_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 isnew_listFor the originalmy_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)

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)


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)


When using this method, it should be noted that all elements in the list must be strings, otherwise they will appearexpected 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]


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 ismy_list[3], and then get it, and then get the element with its index position of 1, that ismy_list[3][1], 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"

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"

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.