Python Learning fifth day List and tuple

Source: Internet
Author: User

List and tuple:

Python provides a type of C-language array, but it is fairly concise to use. Let's talk about the list and tuple in this magical python.

List type:

1. Direct Sticker Code:

L = ['a','B','C']//declares a list  Print L

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

Declares a list type, using an identifier []. It's that simple.

2. Get the number of elements of 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):   " <stdin> "  in <module>indexerror:list index out of range

Python will report a indexerror error when the index is out of range. So, to ensure that the index does not go out of bounds, remember that the index of the last element is len(L) - 1 . (As with the C language array, it starts at index 0.) )

4. Reverse access to the value of the list L element:

>>> l[-1] ' C '>>> l[-2]'B'>>> l[-3]  'A'>>> l[-4]traceback (most recent call last):  " <stdin> "  in <module>indexerror:list index out of range

Oh, my God, Python is a really overbearing language.

5. Insert new elements, inserts, and append.

The list type is a mutable, ordered list. Append Append element End

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

You can also insert a new element between any old element, using the Insert

' AB ' )//represents the position where the index 1 is inserted, and the element after 1 moves back >>> l['A'AB ' ' B ' ' C ' ' D ']

6. Delete element, pop method

>>> L.pop ()//pop method takes no parameters, directly deletes the beginning element, and outputs the deleted element 'A>>> l[  'AB'B'C'  D']

To delete an element at a specified location, using the pop(i) method, where the i index is located:

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

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

' C PLUS '>>> l['B'C PLUS' D ']

The data types of the elements within the IST can also be different, such as:

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

The list element can also be another list, such as

>>> s = ['python''java', ['ASP.  'php'ruby'>> > len (s)4

Note that s there are only 4 elements, one of which s[2] is a list, which is easier to understand if it is disassembled:

>>> p = ['asp. 'php']>>> s = [ ' python ' ' Java ' ' Scheme ']

Or you can think of a two-dimensional array similar to the C language.

To get ‘php‘ can write p[1] or s[2][1] , therefore s can be regarded as a two-dimensional array, similar to three-dimensional, four-dimension ... arrays, but rarely used.

If a list does not have an element, it is an empty list with a length of 0:

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

Another ordered list is called a tuple: a tuple. Tuple and list are very similar, but once the tuple is initialized, it cannot be modified, for example, the name of the classmate is also listed:

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

Now, classmates this tuple cannot be changed, and it does not have a append (), insert () method. Other methods of acquiring elements are the same as lists, and you can use T as normal, [0] T[-1] but you cannot assign a value to another element.

What is the meaning of immutable tuple? Because the tuple is immutable, the code is more secure. If possible, you can use a tuple instead of a list as much as possible.

The trap of a tuple: when you define a tuple, the elements of a tuple must be determined when defined, such as:

>>> T = (1, 2)>>> T (1, 2)

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

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

However, to define a tuple with only 1 elements, if you define this:

>>> t = (1)>>> T1

The definition is not a tuple, it is 1 this number! This is because the parentheses () can represent both tuple and parentheses in the mathematical equation, which creates ambiguity, so Python rules that, in this case, the parentheses are calculated, and the result is naturally 1 .

Therefore, only 1 elements of a tuple definition must be added with a comma , to disambiguate:

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

Python will also add a comma when displaying a tuple of only 1 elements, , lest you misunderstand the parentheses in the mathematical sense.

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

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

This tuple is defined by 3 elements, respectively ‘a‘ , ‘b‘ and a list. Doesn't it mean that once a tuple is defined, it's immutable? Why did you change it later?

Don't worry, let's take a look at the definition when the tuple contains 3 elements:

When we put the list element ‘A‘ and ‘B‘ modify ‘X‘ it to and ‘Y‘ after, 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 is, pointing ‘a‘ , cannot be changed to point ‘b‘ , point to a list, can not 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.

Summary

List and tuple are Python's built-in ordered set, one variable, one immutable . Choose to use them as needed.

Python Learning fifth day List and tuple

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.