Python entry tutorial notes (3) array

19. What is a container and what is a list

In life, a container refers to a container that can hold items. In a program, a container is a data structure that can put multiple elements together. The elements in the container can be iteratively obtained one by one. You can use in, not in Other keywords determine whether an element is contained in the container.

container###

In Python, including lists (list), tuples (tuple), dictionaries (dict), sets (set), etc., they can all be placed in multiple elements, so they can be counted as containers, these containers are in Python programming Very important data structures, we will focus on learning these data structures next.

list

A list (list) is an ordered container. The elements placed in the list will be arranged in a certain order. The method of constructing a list is very simple. Use square brackets [] to enclose the elements that need to be placed in the container to define a list.
For example, list the results of all students:

scores =[45,60,75,86,49,100]

List the names of all students:

names =['Alice','Bob','David','Ellena'] #Note that string elements still need quotes

As we have seen, the list can be put into data types such as numbers, strings, etc. The list does not judge the type put in it, that is to say, the list can put any type of data at the same time, which is determined by the language of Python , Because Python is a dynamic language.

L =['Alice',66,'Bob', True,'False',100]

For list, we can print out the content of list directly.

L =['Alice',66,'Bob', True,'False',100]print(L)

Twenty, visit the list in order

The list is ordered, so we can access the elements in the list in order.

L =['Alice',66,'Bob', True,'False',100]for item in L:print(item)

Recall that in the previous section, we learned about strings. Here, using a for loop to access every element in a list is very similar to using a for loop to access every character in a string.

In fact, a string can also be regarded as a special list, it can only store multiple characters in sequence. The way of accessing each element of the list through a for loop is called iteration.

For an empty list, using for loop access will not print anything.

L =[]for item in L:print(item)

21. Access list by index

Since the list is an ordered container, in the list, each element has a unique position, which we call an index, which is similar to a string, so we can also pass the position Get the elements in the list. Looking back at what we learned earlier, we use square brackets [] to access the corresponding elements by position.
Note that we must pay attention to the distinction here. The definition of the list is also defined by brackets [], but this does not conflict with accessing the elements in the list by index

names =['Alice','Bob','David','Ellena']print(names[0])print(names[1])print(names[2])print(names[3])

Since names has only four elements, we can only access the last element through index 3. Just imagine, what if we print(names[4])?

names =['Alice','Bob','David','Ellena']print(names[4])

In fact, this will cause Python runtime errors, suggesting that index access is out of range.

Traceback(most recent call last):
 File "<stdin>", line 1,in<module>
IndexError: list index out of range

Therefore, when we use the index to access the list, we must pay special attention not to cross the boundary.

At the same time, lists, like strings, also support slicing. By slicing, you can obtain sublists of the list.

names =['Alice','Bob','David','Ellena']
sub_names = names[0:2]print(sub_names)

It should be noted here that if we slice beyond the boundary, there will be no Python runtime error, but if we slice according to such a subscript, we will not get any elements.

names =['Alice','Bob','David','Ellena']
sub_names = names[5:10]print(sub_names) # ==>[]

Two, three, reverse access list

Python lists, in addition to supporting forward order indexing to get each element in the list, it also supports accessing each element in the list in reverse order.

names =['Alice','Bob','David','Ellena']

For the names list, the name of Ellena is at the end, which is what we call the last one. In Python, you can use -1 to represent the last element.

names =['Alice','Bob','David','Ellena']print(names[-1]) # ==> Ellena

In the same way, we can use -2 to print out the name of David, and use -3 to print out the location of Bob.

print(names[-2]) # ==> David
print(names[-3]) # ==> Bob

Note that if we use -5, because there is no fifth-to-last name, this is also an out-of-bounds, and an error will also be reported.

names =['Alice','Bob','David','Ellena']print(names[-5])Traceback(most recent call last):
 File "<stdin>", line 1,in<module>
IndexError: list index out of range

Two or four, add new elements to the list##

Now there are 4 students in the class:

names =['Alice','Bob','David','Ellena']

Today, a new classmate, Candy, was transferred to the class. How to add the new classmate to the existing list?
In Python, list provides a series of methods that allow us to manipulate the elements in the list, which also includes methods for adding elements.
The first way is to use the append() method to append new students to the end of the list:

names =['Alice','Bob','David','Ellena']
names.append('Candy')print(names) # ==>['Alice','Bob','David','Ellena','Candy']

Note that the append() method always adds the element to the end of the list.
If the above list needs to be sorted by the first letter, then Candy should be ranked third. What should I do?

This requires the use of the insert() method of the list. The insert() method is different from the append() method. The insert() method requires two parameters, which are the position to be inserted and the element to be inserted.

names =['Alice','Bob','David','Ellena']
names.insert(2,'Candy')print(names) # ==>['Alice','Bob','Candy','David','Ellena']

Note that after inserting Candy into the third position, the original name will automatically move one place back. At this time, if you use the same index to get the following elements, you will get different results

names =['Alice','Bob','David','Ellena']print(names[2]) # ==> David
names.insert(2,'Candy')print(names[2]) # ==>Candy

25. Remove elements from the list##

If Ellena needs to transfer due to family reasons, how do we delete Ellena from the existing list?

At this time, we can use the pop() method of the list. The pop() method deletes the last element of the list by default and returns.

L =['Alice','Bob','Candy','David','Ellena']
name = L.pop()print(name) # ==> Ellena
print(L) # ==> L =['Alice','Bob','Candy','David']

For Ellena, because Ellena happens to be at the end of the list, you can directly use the pop() method to delete Ellena from the end of the list. If it is not Ellena that needs to be transferred, but Candy, what should I do at this time?

In the pop() method, in addition to deleting the last element, pop() can also receive a parameter to specify the position of the element to be deleted.

L =['Alice','Bob','Candy','David','Ellena']
name = L.pop(2)print(name) # ==> Candy
print(L) # ==>['Alice','Bob','David','Ellena']

26. Replace elements in list##

For a list, in addition to adding elements to the list and deleting list elements, the existing elements of the list can also be modified. The original elements in the list can be replaced by specifying the position by index and assigning a new element.

If the classmate Candy needs to transfer away and a new classmate Canlina transfers in at the same time, then in alphabetical order, Canlina's position happens to be Candy's position.

L =['Alice','Bob','Candy','David','Ellena']
L[2]='Canlina'print(L)

We can also use the reverse index to accomplish the same function.

L =['Alice','Bob','Candy','David','Ellena']
L[-3]='Canlina'print(L)

Note that if you replace a subscript that does not exist, it will also cause Python runtime errors.

L =['Alice','Bob','Candy','David','Ellena']
L[6]='Canlina'Traceback(most recent call last):
 File "<stdin>", line 1,in<module>
IndexError: list assignment index out of range

Two-seven, two-dimensional list

Sometimes, a one-dimensional list does not meet all the requirements (all the above lists are one-dimensional lists). At this time, a two-dimensional list or even a higher-dimensional list is required.

such as:
Alice’s latest three results are [100, 89, 92]
Bob’s latest three results are [70, 65, 81]
Candy’s latest three results are [88, 72, 77]
If you need to store the results of three students in a list, you need to do this:

alice_scores =[100,89,92]
bob_scores =[70,65,81]
candy_scores =[88,72,77]
all_scores =[alice_scores, bob_scores, candy_scores]print(all_scores) # ==>[[100,89,92],[70,65,81],[88,72,77]]

What you get at this time is a two-dimensional list. For a two-dimensional list, each element in the list is still a list. At this time, if you need to get Bob's latest third test score from the two-dimensional list all_scores, you can write:

alice_scores =[100,89,92]
bob_scores =[70,65,81]
candy_scores =[88,72,77]
all_scores =[alice_scores, bob_scores, candy_scores]
score = all_scores[1][2] # ==>81

Among them, all_scores[1] gets a list of Bob's three most recent scores, and then through the subscript [2], you can get Bob's third score.

Recommended Posts

Python entry tutorial notes (3) array
Python notes
Python entry-3
Python entry notes [basic grammar (below)]
Python2.7 [Installation Tutorial]
Python study notes (1)
python study notes
python print array
Python study notes (3)
Python entry learning materials
03. Operators in Python entry
Python basic drawing tutorial (1)
python array add array_Python add array
Python3 entry learning four.md
Python3 entry learning three.md
Python3 entry learning one.md
Python3 entry learning two.md
Python basic drawing tutorial (two)
Python implements multi-dimensional array sorting
Create Python two-dimensional array correctly
05. Python entry value loop statement
Python introductory notes [basic grammar (on)]
Python from entry to proficiency (2): Introduction to Python