Create List
One of the data types built into Python is the list: list
. A list is an ordered set of elements that can be added and removed at any time.
For example, by listing the names of all the classmates in the class, you can use a list to indicate:
>>> [' Michael ', ' Bob ', ' Tracy ' [' Michael ', ' Bob ', ' Tracy ']
A list is an ordered set of mathematical meanings, that is, the elements in the list are arranged in order.
Constructing the list is very simple, [ ]
just by enclosing all the elements of the list in the code above, which is a list object. In general, we assign a list to a variable so that we can refer to the list by a variable:
>>> classmates = [' Michael ', ' Bob ', ' Tracy ']>>> classmates # Print the contents of the classmates variable [' Michael ', ' Bob ', ' Tracy ']
Because Python is a dynamic language, the elements contained in the list do not necessarily require the same data type, and we can include all kinds of data in the list:
>>> L = [' Michael ', +, True]
An element that does not have a list is an empty list:
>>> empty_list = []
Task
Suppose there are 3 students in the class: Adam,lisa and Bart, their grades are 95.5,85 and 59, please follow the name, score, name, score ... The order is represented by a list of points from high to low, and then printed out.
Access list by index
Since list is an ordered set, we can use a list to indicate from high to low the 3 students in the class:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
So how do we get the names of the nth-named students from the list? The method is to get the specified element in the list by index.
It is important to note that the index starts at 0, that is, the index of the first element is 0, the second element is indexed by 1, and so on.
Therefore, to print the first name of a classmate, use L[0]:
>>> Print L[0]adam
To print the name of the first two students, use L[1]:
>>> Print L[1]lisa
To print the name of the first three students, use L[2]:
>>> Print L[2]bart
To print the name of the first four students, use L[3]:
>>> Print L[3]traceback (most recent call last): File "<stdin>", line 1, in <module>indexerror:l Ist index out of range
The error! Indexerror means that the index is out of range because the list above has only 3 elements, and the valid index is 0,1,2.
Therefore, when using an index, be careful not to cross the border .
Task
The results of three students can be represented by a list:
L = [95.5, 85, 59]
Please print the score for first, second, third, fourth, respectively, according to the index.
Reverse access list
We still use a list to score from high to low to show 3 students in the class:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
At this time, the teacher said, please score the lowest students stand out.
To write code to accomplish this task, we can count the list first and find that it contains 3 elements, so the index of the last element is 2:
>>> Print L[2]bart
Is there a simpler way?
Yes!
Bart classmate is the last, commonly known as the countdown first, so we can use the 1 index to represent the last element:
>>> Print L[-1]bart
Bart classmate says lying on the gun.
Similarly, the second-to-last use-2 means that the reciprocal third use-3 means that the penultimate fourth uses-4 means:
>>> print l[-2]lisa>>> print l[-3]adam>>> print l[-4]traceback (most recent call last): File "<stdin>", line 1, inch <module>indexerror:list index out of range
L[-4] Error, because the penultimate fourth does not exist, there are only 3 elements.
When using a reverse index, also be careful not to cross the border .
Task
The results of three students can be represented by a list:
L = [95.5, 85, 59]
Please print the number of the penultimate, penultimate, penultimate, and fourth-lowest points according to the reverse index.
Add new Element
Now, there are 3 students in the class:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
Today, the class transferred to a new classmate Paul, how to add new students to the existing list?
The first option is to append the append()
new classmate to the end of the list by using the list method:
>>> L = [' Adam ', ' Lisa ', ' Bart ']>>> l.append (' Paul ') >>> print l[' Adam ', ' Lisa ', ' Bart ', ' Paul ' ]
append () always adds a new element to the tail of the list.
What if Paul says he is always on the test and asks to be added to the first place?
The method is to use the list insert()
method, which accepts two parameters, the first parameter is the index number, and the second parameter is the new element to be added:
>>> L = [' Adam ', ' Lisa ', ' Bart ']>>> l.insert (0, ' Paul ') >>> print l[' Paul ', ' Adam ', ' Lisa ', ' Bar T ']
l.insert (0, ' Paul ') means that ' Paul ' will be added to the position of index 0 (i.e. the first one), while Adam, who originally indexed 0, and all the classmates behind it, automatically move backwards.
Task
Let's say that a new student paul,paul a classmate better than Bart, but worse than Lisa, he should be in the third place, please use the code to achieve.
Delete an element from list
Paul's classmates had to turn away a few days ago, so how do we remove Paul from the existing list?
If Paul's classmates were in the last one, we could delete them using the list pop()
method:
>>> L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']>>> L.pop () ' Paul ' >>> print l[' Adam ', ' Lisa ', ' Bart ']
The pop () method always deletes the last element of the list, and it returns the element, so we print out ' Paul ' after we execute L.pop ().
What if Paul's classmates aren't the last one? For example, Paul is ranked third:
>>> L = [' Adam ', ' Lisa ', ' Paul ', ' Bart ']
To kick Paul out of the list, we have to locate Paul's position first. Since Paul's index is 2, use Paul to erase it pop(2)
:
>>> L.pop (2) ' Paul ' >>> print l[' Adam ', ' Lisa ', ' Bart '
Task
Note the list in the editor code on the right is as follows:
L = [' Adam ', ' Lisa ', ' Paul ', ' Bart ']
Paul's index is 2,bart's index is 3, if we want to erase both Paul and Bart, please explain why the following code does not work correctly:
L.pop (2)
L.pop (3)
How can I adjust the code to remove both Paul and Bart correctly?
Replace element
Let's say the class is still 3 students:
>>> L = [' Adam ', ' Lisa ', ' Bart ']
Now, Bart's classmates are going to transfer, and happened to be a Paul classmate, to update the class membership list, we can first delete Bart, and then add Paul in.
Another way is to replace Bart with Paul directly:
>>> l[2] = ' paul ' >>> print LL = [' Adam ', ' Lisa ', ' Paul ']
To assign a value to an index in a list, you can replace the original element with the new element directly, and the list contains the same number of elements.
Since Bart can also index by-1, the following code can also do the same job:
>>> l[-1] = ' Paul '
Task
The students in the class rank according to the score:
L = [' Adam ', ' Lisa ', ' Bart ']
However, after an exam, Bart's classmates accidentally made the first, and Adam classmate test the last.
Create a new rank by assigning a value to the index of the list.
Create a tuple
Tuple is another ordered list, and Chinese is translated as "tuple". Tuple and list are very similar, however, once a tuple is created, it cannot be modified.
The same is the name of the class, expressed as a tuple as follows:
>>> t = (' Adam ', ' Lisa ', ' Bart ')
The only difference between creating a tuple and creating a list is the ( )
substitution [ ]
.
Now, this t
cannot be changed, the tuple has no append () method, and there is no insert () and Pop () method. Therefore, the new classmate can not directly add to the tuple, old classmates want to quit a tuple also not.
The way to get a tuple element is exactly the same as the list, and we can access the element normally using indexed methods such as t[0],t[-1], but cannot be assigned to any other element, but it is not believed to try:
>>> t[0] = ' Paul ' Traceback (most recent): File "<stdin>", line 1, in <module>typeerror: ' Tuple ' object does not support item assignment
Task
Create a tuple that contains 0-9 of these 10 numbers in order.
Supplementary Note: If the range (0,10) function is used to produce a sequence, not a tuple;
Several uses of the range () function are listed first:
function Prototypes : Range (start, end, scan):
parameter meaning : Start: Count starts from start. The default is starting from 0. For example, range (5) is equivalent to range (0, 5);
End: The technology ends with end, but does not include end. For example: Range (0, 5) is [0, 1, 2, 3, 4] No 5
Scan: The distance between each hop is 1 by default. Example: Range (0, 5) is equivalent to range (0, 5, 1)
To create a cell element tuple
Tuple and list, can contain 0, one and any number of elements.
A tuple that contains multiple elements, which we have created earlier.
A tuple of 0 elements, which is an empty tuple, is represented directly by ():
>>> t = () >>> print t ()
What about creating a tuple with 1 elements? To try:
>>> t = (1) >>> print T1
It seems to be wrong! T is not a tuple, but an integer 1. Why is it?
Because ()
both can represent a tuple and can be used as parentheses to indicate the priority of the operation, the result (1) is calculated by the Python interpreter as result 1, which results in not being a tuple, but an integer 1.
It is precisely because the tuple with the () definition of a single element is ambiguous, so Python specifies that the element tuple should have a comma ",", which avoids ambiguity:
>>> T = (1,) >>> print T (1,)
Python also automatically adds a "," when printing cell tuples, in order to tell you more explicitly that this is a tuple.
The multivariate tuple plus does not add this extra "," effect is the same:
>>> T = (1, 2, 3,) >>> print T (1, 2, 3)
Task
Please indicate why the code in the editor on the right did not create a tuple with a student:
t = (' Adam ')
Print T
Please modify the code to make sure T is a tuple.
"Variable" tuple
We saw in the front that the tuple cannot be modified once it is created. Now, let's look at a "mutable" tuple:
>>> t = (' A ', ' B ', [' A ', ' B '])
Notice that T has 3 elements:' A ', ' B ' and a list:[' A ', ' B ']. List as a whole is the 3rd element of a tuple. The list object can be obtained by t[2]:
>>> L = t[2]
Then we change the list's two elements:
>>> l[0] = ' X ' >>> l[1] = ' Y '
Then look at the contents of the tuple:
>>> print T (' A ', ' B ', [' X ', ' Y '])
Doesn't it mean that once a tuple is defined, it's immutable? What's the change now?
Don't worry, let's take a look at the definition when the tuple contains 3 elements:
When we modify the list's Elements ' A ' and ' B ' to ' X ' and ' Y ', the tuple becomes:
On the surface, the elements of a tuple do change, but in fact it is not a tuple element, but a list element.
The list that the tuple initially points to is not changed to another list, so the so-called "invariant" of a tuple is that each element of a tuple is directed to never change. That point ' a ', it cannot be changed to point to ' B ', pointing to a list, cannot be changed to point to other objects, but the list itself is variable!
After understanding "point to Invariant", how do you create a tuple that does not change the content? It is important to ensure that each element of a tuple cannot be changed.
Task
A tuple is defined:
t = (' A ', ' B ', [' A ', ' B '])
Because t contains a list element, the contents of the tuple are mutable. Can you modify the above code so that the tuple content is not mutable?
Getting Started with Python (iv) list and tuple types