Python--list and tuple types--2

Source: Internet
Author: User

Original blog, reprint please indicate the source--Zhou Xuewei http://www.cnblogs.com/zxouxuewei/

一.创建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.

The

Constructs the list is very simple, according to the above code, directly with [] all elements of the list are enclosed, is a list object. Typically, we assign a list to a variable so that you 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 = []
Two. 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):  "<stdin> " 1  in <module> 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 .

Three. 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 (recent)  :"<stdin>"1in <module> 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 .

Four. Adding new elements

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

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.

Five. Deleting an element from the 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 ']
Six. Replacing elements

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'>>>= ['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'
Seven. Create Tupletuple is another ordered list, Chinese translated as "tuples". 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):  "  <stdin>"1 in <module>"tuple  'object does not support item assignment
Eight. 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 = (123,)>>> print t (123 
Nine. " 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 theso-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.

Python--list and tuple types--2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.