The goal of snowball Learning Python is to make Python bigger and bigger.

This series of articles will be completed before the Spring Festival of 2021, welcome to follow, like, comment -- dream eraser

After learning Python, you can learn half of it

4.1 What is a list

A list is a Python data type that can be dynamically added or removed. It consists of a series of elements. To put it bluntly, a list is a container that combines variables together.

Many articles will look for a programming concept similar to lists. It will be said that lists in Python are just like arrays in other languages, but arrays are also a strange concept to students who have no programming concepts at all. A list in Python is a container that can hold variables of any data type.

4.1.1 List Definition

The format of the list definition is as follows

My_list = [element1Elements,2Elements,3...]
Copy the code

Each piece of data in a list is called an element or item, the list is wrapped with [], each element is separated by English, and the list can be printed directly.

my_list = ["apple"."orange"."grape"."pear"]
print(my_list)
Copy the code

The elements in a list can be of the same or different data types, so nesting lists is also possible.

my_list = [1."orange".True.1.0[1.2.3]]
print(my_list)
Copy the code

4.1.2 List Reading

To read a list, you need to learn two nouns, one is index, the other is subscript. These two words have the same meaning, and they are used to accurately retrieve the elements in the list. Index can be simply understood as the concept of serial number.

The first thing you need to learn is that indexes in a list start at 0, which is a bit of a shock at first, but will get better once you get used to it. Just like when we start counting numbers from 1, suddenly we need to start counting numbers from 0.

Take a look at the list, for example, and try to read the index of each element in Chinese.

my_list = ["apple"."orange"."grape"."pear"]
Copy the code

The element with index 0 is the string apple, the element with index 1 is the string orange, and so on.

The syntax for reading a list is as follows:

# list name [index]
my_list[i]
Copy the code

This is translated into Python code:

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])
Copy the code

When retrieving an element from an index, it is important to note that the index starts at 0 and is easily forgotten…… Oh ~

The index can be negative as well as positive, and the last element in the list is indexed -1 as follows:

nums = [1.2.3.4.5.6]
print(The last element in the list is:,nums[-1])
Copy the code

In order, -1 is the last element, -2 is the second-to-last…

4.1.3 List Slicing

When writing programs to manipulate lists, you often see the following scenarios.

  • Obtain 1~3 elements;
  • 4~7 elements were obtained.
  • Get 1,3,5… Item elements.

This translates into the actual encoding of the list, known as the slicing operation, which is the action of slicing meat that you’re seeing in your mind right now. The syntax is as follows:

Read the list elements from index m to n-1
my_list[m:n]
Read the first n elements of the list
my_list[:n]
Read elements from m to the end of the list
my_list[m:]
# interval s, read list elements from m to n
my_list[m:n:s]
Copy the code

The above content is reflected in the code as follows. This part is displayed in the code as follows, paying particular attention to the values of m and n.

my_list = ["a"."b"."c"."d"."e"."f"]

['a', 'b', 'c'] note that the indexes of a,b, and c are 0,1,2 respectively
print(my_list[0:3])
# output [' b ', 'c', 'd', 'e'] note b, c, d, e subscripts 1, 2, 3, 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])
# print ['b', 'd'] from index 1 to index 3, interval 1
print(my_list[1:4:2])
Copy the code

List slicing is a very important topic in Python. The key is to understand how indexes correspond to each element in a list.

4.1.4 List-related built-in functions

There are four common built-in functions related to lists in Python, namely to get the maximum value Max, the minimum value min, the sum sum, and the number of list elements len.

Maximum and minimum

The Max and min functions can be used to directly obtain the maximum and minimum values in the list. There are some precautions for using this function. 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]

F # output
print(max(my_list1))
# 6 output
print(max(my_list2))
# error
print(max(my_list3))
Copy the code

At run time, the above code finds that the first two lists output maximum values, but the third one directly returns an error. This is because Max and min can only be used for lists that are all numbers or strings, and an error is reported if there are other data types in the list or if numbers and strings are mixed.

Min is used exactly the same as Max, without trying to write code.

The sum function can be used to get the sum of the elements in the list, but it is important to note that sum cannot be used for non-numeric elements, which means the following code is incorrect.

my_list1 = ["a"."b"."c"."d"."e"."f"]
print(sum(my_list1))
Copy the code

Len = len = len = len = len = len = Len = Len = Len = len = len = len

4.1.5 Modify and delete list elements

For a list datatype variable, it is possible to modify and delete elements, which is why the list mentioned at the beginning of this article is a Python datatype that can be dynamically added and deleted. (This section does not yet allow dynamic addition of lists, as explained later.) The elements of the list can be modified by retrieving the index.

my_list1 = ["a"."b"."c"."d"."e"."f"]
print("List before Modification",my_list1)
my_list1[4] = eraser
print("Revised list",my_list1)
Copy the code

The deletion operation of list elements can be divided into two cases. Simply speaking, one is to delete a single element and the other is to delete multiple elements. Delete and list slice correlation is very high, comparable to the following code for learning.

my_list1 = ["a"."b"."c"."d"."e"."f"]

Delete an element by index
del my_list1[0]
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)
Copy the code

The key word used in the delete operation is del. The key point, as you probably already know, is to find the element by index and then delete the element by del.

Note that you are manipulating elements in a list, but now you will learn how to manipulate a complete list.

4.1.6 Add, multiply, and delete lists

In Python, you can add and multiply lists directly, and the addition of lists can be interpreted as joining lists, as follows:

my_list1 = ["a"."b"]
my_list2 = ["c"]
my_list3 = my_list1 + my_list2
print(my_list3)
Copy the code

Any number of lists that operate directly with “+” will be joined together to form a new large list.

Lists can be multiplied by a number to repeat the previous list multiple times, as in the following code:

my_list1 = ["a"."b"]
my_list2 = ["c"]
my_list3 = my_list1 * 4
['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
print(my_list3)
Copy the code

The above code uses [a,b] * 4 to get the list [a,b] repeated four times.

4.2 Introduction to Python Object Orientation

Python is an object-oriented programming language, so all the data in Python is an object, such as before learning to the list of integers, floating point number, string, are objects, don’t make much explanation about object-oriented concepts (such as after all now explanation is futile, specific learn object-oriented part in).

We can design methods for various objects. These methods are also functions in a general sense. If this sounds a bit convoluted, there are already built-in methods for some basic objects in Python.

The syntax for calling an object method is:

Object.method ()Copy the code

4.2.1 Methods for string objects

The first thing you need to know is that in Python any data is an object, so once you declare a string variable, that string variable is an object, and if it’s an object, it has methods on that object. Common methods for strings are:

  1. Lower converts the string to lowercase
  2. Upper converts the string to uppercase
  3. Title uppercase the first letter of the string and lower case the rest
  4. Rstrip removes whitespace 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()

# capitalized
print(my_strU)
# lowercase
print(my_strL)
# Uppercase
print(my_strT)
Copy the code

The output is as follows:

GOOD MORING
good moring
Good Moring
Copy the code

It’s useful to remove whitespace from the beginning or end of a string and leave it to yourself. See my_str.strip() for the code.

4.2.1 Quick access to the built-in system

In practice, it is very difficult to remember all the methods of an object. For eraser, when writing code, we also need to use the manual. There are too many methods that can not be remembered. 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))
Copy the code

When the code runs, you get something like this, where the red box is the method I just mentioned.

To learn how a method is used, you can call the built-in help function you learned earlier. The syntax is as follows:

Help (object. Methods)

An example is the rfind method for getting string objects.

my_str = "good moring"

print(help(my_str.rfind))
Copy the code

The results are as follows, and a quick read will give you an idea of how the Rfind method is used.

Let’s take a look at the list method because we’re going to continue with the list method, so I’m going to do a quick demonstration.

my_list1 = ["a"."b"]
print(dir(my_list1))
Copy the code

The red box methods will be covered in the rest of this blog, but I’m sure some of you will be interested in the ones that don’t start with a double _ in the red box. They’re methods, too, but it’s not time to learn them yet.

4.3 Adding and deleting list elements using methods

4.3.1 Append elements to a list

When operating on a list, you often need to append elements to an existing list. For example, the original list has one element and now you want to append two. If you directly set the index value, an error message is displayed indicating that the index value exceeds the length of the list. Note that this error often occurs when you operate the list.

my_list = ["apple"."orange"."grape"]
my_list[3] = "pear"
Copy the code

IndexError: List Assignment Index out of range error message IndexError: List Assignment Index out of range error message IndexError: List Assignment Index out of range

To append elements to a list, Python has a built-in method for the list object in the following format.

my_list.append("New element")
Copy the code

For example, you can then declare an empty list and append elements to that list.

my_list = []
my_list.append("pear")
my_list.append("apple")
my_list.append("orange")

print(my_list)
Copy the code

The append method appends one element at a time to the end of the list, which allows you to extend the list indefinitely.

4.3.2 Insert elements into the list

The append method inserts an element at the end of a list. Insert is a new method called insert. The syntax is as follows:

My_list. insert(index position,"New element")
Copy the code

Insert element at index 1, index 2, index 0 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)
Copy the code

Note that when the index exceeds the list length, the end is inserted by default.

4.3.3 Deleting list elements

The problem with deleting a list element using the keyword del was that no element was retrieved after the element was deleted. The next method to solve this problem is pop, and you can retrieve the deleted value. The method is pop, and the syntax is as follows:

Item = my_list.pop() item = my_list.pop(index)Copy the code

Note that the POP method can carry an index value and delete the element at the index position directly, if not the last item by default. The item variable is used to get the deleted value. Note that when this method deletes an element, the index cannot exceed the list length.

my_list = ["pear"."apple"."orange"]
item = my_list.pop()
print(item)

print("After deleting elements")
print(my_list)
Copy the code

The code runs as follows:

Orange deletes the element ['pear'.'apple']
Copy the code

The pop method removes an element by index. You can also remove an element by removing it.

My_list.remove (Contents of elements to be removed)Copy the code

Note that remove does not return the deleted element after it has been removed, and there is a problem with a code error if the element to be removed is not in the list.

If more than one element appears in the list, only the first element is deleted by default. If you want to delete more than one element, you need to use the following loop knowledge.

4.4 Sorting a List

In addition to adding, deleting and modifying lists, sorting is also involved. This operation is also very simple for list objects, using a fixed method.

4.4.1 sort order

The sort method is used to sort a list of numeric or English characters. If the data type of the elements in the list is complex, this method is not applicable.

The syntax of the sort method is as follows:

my_list.sort()
Copy the code

Declare a list where all elements are numbers, and sort it.

my_list = [3.4.1.2.9.8.7]
print("Before sorting:", my_list)

my_list.sort()
print("After sorting:", my_list)
Copy the code

The following output is displayed:

Before ordering: [3, 4, 1, 2, 9, 8, 7] sorted: [1, 2, 3, 4, 7, 8, 9]Copy the code

If you want to sort from top to bottom, you simply add the parameter reverse=True (more on parameter concepts 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)
Copy the code

I hope you can test the sorting result of The English string. You need to pay attention to the sorting of the English character list. It is recommended to change the English string to lowercase.

Note that the sort method above changes the order of the elements in the list, i.e. changes the order of my_list. If you want to create a new list without changing the order of the list, you need to use the following method.

4.4.2 sorted order

In this case, use the sorted function. Note that sorted is a built-in function, not a method of a list object. In other words, sorted can be used to sort many objects.

The sorted function has the following syntax:

sorted(List to be sorted)# Positive order, from small to large
sorted(List to be sorted,reverse=True) # Reverse, from large to small
Copy the code

This function returns a new list, which you can receive with a new variable, 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)
Copy the code

Note that the new variable new_list has no effect on the order of the elements in the my_list list.

4.5 List other methods

4.5.1 List Retrieval Element index

The index method is used to obtain the index value of the first occurrence of an item in a list in the following format:

Index value = my_list.index(to be found)Copy the code

This method notices an error if the index value is not retrieved.

my_list = [3.4.1.2.9.8.7]
ke = my_list.index(4)
ke = my_list.index(10)
print(ke)
Copy the code

4.5.2 Number of statistical elements in the list

The count method is used to get the number of occurrences of a particular element in a list. The syntax is as follows:

Count = my_list.count(to be found)Copy the code

This method also returns 0 if no value is found in the list.

my_list = [3.4.3.2.3.8.7]
nums = my_list.count(3)

print(nums)
Copy the code

4.5.3 Converting lists to Strings

The join method combines all the elements in a list into a string in the following syntax:

Join string. Join (list to convert)Copy the code

This method is actually a method of a string object.

my_list = ["pear"."apple"."orange"]
my_str = "#".join(my_list)

print(my_str)
Copy the code

When using this method, note that all elements in the list must be strings. Otherwise, the expected STR instance, int found error will occur.

4.5.4 List Appends a list

The append method can append elements to lists, and extend can append a list to a list, concatenating two lists.

The list of1.The extend (list2)
Copy the code

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 since the appended list.

my_list1 = [1.2.3]
my_list2 = [4.5.6]

my_list1.extend(my_list2)
print(my_list1)
Copy the code

4.6 Multidimensional Lists

The elements in a list can be of any data type, so nested lists are also possible.

my_list = [1.2.3[4.5.6]]
Copy the code

For example, if you want to obtain element 5, you should first obtain the fourth element in the outermost list, namely my_list[3], and then obtain the element whose index position is 1, namely, my_list[3][1]. The specific code can be tried out on its own, or it can be nested in the inner list and looped endlessly.

4.7 Special List Strings

Now back to the string format of “abcsdasa”, you can think of a string asa list of characters, also known asa sequence of characters (an ordered list), and a string is not exactly equivalent to a list because you can’t modify a single element in a string.

4.7.1 String Indexing and Slicing

A string can also access an element through an index, which is used in the same way as a list, for example:

my_str = "abcdefghi"
print(my_str[5])
print(my_str[4])
print(my_str[3])
Copy the code

List slicing can also be used for strings, equivalent to getting string substrings.

4.7.2 Partial functions and methods available for strings

Built-in list-related methods, such as len, Max, and min, are also available for strings, and you can experiment with them yourself.

4.7.3 Converting strings to lists

A string can be converted to a list using the built-in function list, which undoes each character in the string.

my_str = "abcdefghi"
print(list(my_str))
Copy the code

The output is:

['a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'.'i']
Copy the code

4.8 Summary of this blog

Lists are very important data types in basic Python. While writing this blog, I was wondering if I should include everything in it, only to find that there are too many, many of which are very relevant. In this blog, I have also taken a look at some of the simplest concepts of object orientation.

What is omitted in this blog will be filled in later.

  • Deep replication and shallow replication
  • The concept of address
  • In, not in expressions
  • Is, is not expressions
  • Enumerate objects

I hope I can see your comments when I explain these contents.

The last bowl of chicken soup

There is nothing I can’t mess up as long as I work hard

💎 💎 💎 💎 💎 💎 💎 💎 💎 💎 💎


Today is the 3/100th day of continuous writing. If you have ideas or techniques you’d like to share, feel free to leave them in the comments section.


Blogger ID: Dream eraser, hope you like, comment, favorites.