Python learning day 5 List and tuple, pythontuple

Source: Internet
Author: User

Python learning day 5 List and tuple, pythontuple

List and tuple:

Python provides a type similar to the C language array, but it is quite simple to use. Let's talk about list and tuple in this magical python.

List type:

1. Directly paste the Code:

L = ['A', 'B', 'C'] // declare A Listprint L

Output ['A', 'B', 'C']

Declare a List type and use the identifier.

2. Obtain the number of elements in List L:

>>> len(L)3

3. Access the value of the List L element:

>>> L[0]'A'>>> L[1]'B'>>> L[2]'C'>>> L[3]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

When the index is out of the range, Python will report an IndexError. Therefore, make sure that the index does not cross-border. Remember that the index of the last element islen(L) - 1. (Like the C language array, the index starts from 0 .)

4. Access the value of the List L element in reverse order:

>>> L[-1]’C‘’>>> L[-2]'B'>>> L[-3]'A'>>> L[-4]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

The language of python is really domineering.

5. insert new elements, insert and append.

The List type is a variable ordered List. Append

>>> L.append('D')>>> L['A', 'B', 'C', 'D']

You can also insert a new element between any old one and use insert

>>> L. insert (1, 'AB') // indicates the position where index 1 is inserted. elements after Index 1 are moved backward> L ['A', 'AB', 'B ', 'C', 'D']

6. Delete elements and pop Methods

>>> L. pop () // The pop method directly deletes the element starting with A parameter without parameters, and outputs the deleted element 'A' >>> L ['AB', 'B ', 'C', 'D']

To delete the element at the specified position, usepop(i)Method, whereiIs the index location:

>>> L.pop(1)'AB'>>> L['B', 'C', 'D']

To replace an element with another element, you can directly assign a value to the corresponding index location:

>>> L[1] = 'C PLUS'>>> L['B', 'C PLUS', 'D']

The Data Types of elements in the ist can also be different, for example:

>>> L = ['Apple', 123, True]

The list element can also be another list, such

>>> s = ['python', 'java', ['asp.net', 'php'], 'ruby']>>> len(s)4

Note:sThere are only four elements, of whichs[2]It is also a list, which is easier to understand if it is split and written:

>>> p = ['asp.net', 'php']>>> s = ['python', 'java', p, 'scheme']

Or it can be considered to be similar to a two-dimensional array in C language.

To get'php'Writablep[1]Ors[2][1], SosIt can be seen as a two-dimensional array, similar to 3D, four-dimensional ...... Array, but rarely used.

If no element exists in a list, it is an empty list with a length of 0:

>>> L = []>>> len(L)0
Tuple type

Another ordered list is tuple. Tuple and list are very similar, but tuple cannot be modified once initialized. For example, they are also used to list the names of students:

>>> T = ('A', 'B', 'C')

Now, the tuple of classmates cannot be changed.There is no such thing as append () or insert ().Method. Other methods for retrieving elements are the same as those for listing. You can use T normally.[0],T[-1]But cannot be assigned to another element.

What is the significance of an immutable tuple? Because tuple is immutable, the code is safer. If possible, use tuple instead of list.

Tuple trap: When you define a tuple, The tuple elements must be determined. For example:

>>> t = (1, 2)>>> t(1, 2)

If you want to define an empty tuple, you can write it():

>>> t = ()>>> t()

However, to define a tuple with only one element, if you define it as follows:

>>> t = (1)>>> t1

Tuple is not defined, yes1This number! This is because of parentheses.()It can represent both tuple and parentheses in the mathematical formula, which leads to ambiguity. Therefore, Python stipulates that, in this case, the calculation result is naturally1.

Therefore, a comma must be added when only one tuple element is defined.,To eliminate ambiguity:

>>> t = (1,)>>> t(1,)

When Python displays a tuple with only one element, it also adds a comma,To avoid misunderstanding into parentheses in the mathematical sense.

Finally, let's look at a "variable" tuple:

>>> t = ('a', 'b', ['A', 'B'])>>> t[2][0] = 'X'>>> t[2][1] = 'Y'>>> t('a', 'b', ['X', 'Y'])

This tuple defines three elements:'a','b'And a list. Doesn't tuple be immutable once defined? Why have they changed?

Don't worry. Let's take a look at the three elements that tuple contains when defining:

When we put the list element'A'And'B'Change'X'And'Y'Then, tuple becomes:

On the surface, the tuple elements have indeed changed, but in fact they are not the tuple elements, but the list elements. The list pointed to by tuple is not changed to another list. Therefore,Tuple's so-called "unchanged" means that every element of tuple is always pointed.Point'a'And cannot be changed'b', Pointing to a list, you cannot point to other objects, but the list itself is variable!

After "pointing to unchanged", how does one create a tuple with unchanged content? Therefore, each element of the tuple cannot be changed.

 

Summary

List and tuple are ordered collections built in Python,One variable and one immutable. Use them as needed.

Related Article

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.