Python data type list (list), tuple (tuples), pythontuple

Source: Internet
Author: User

Python data type list (list), tuple (tuples), pythontuple
List

A built-in data type in Python is list: list. List is an ordered set that allows you to add and delete elements at any time.

For example, you can use a list to list the names of all the students in the class:

1 >>> classmates = ['Michael', 'Bob', 'Tracy']2 >>> classmates3 ['Michael', 'Bob', 'Tracy']

VariableclassmatesIs a list. Uselen()The function can obtain the number of list elements:

1 >>> len(classmates)2 3

Use indexes to access the elements at every position in the list. Remember that the index is from0Start:

 1 >>> classmates[0] 2 'Michael' 3 >>> classmates[1] 4 'Bob' 5 >>> classmates[2] 6 'Tracy' 7 >>> classmates[3] 8 Traceback (most recent call last): 9   File "<stdin>", line 1, in <module>10 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 the border. Remember that the index of the last element islen(classmates) - 1.

To obtain the last element, you can use-1Index to directly obtain the last element:

1 >>> classmates[-1]2 'Tracy'

And so on, you can get 2nd to the last and 3rd to the last:

1 >>> classmates[-2]2 'Bob'3 >>> classmates[-3]4 'Michael'5 >>> classmates[-4]6 Traceback (most recent call last):7   File "<stdin>", line 1, in <module>8 IndexError: list index out of range

Of course, the last 4th will be out of the border.

List is a variable ordered table. Therefore, you can append an element to the end of the list:

1 >>> classmates.append('Adam')2 >>> classmates3 ['Michael', 'Bob', 'Tracy', 'Adam']

You can also insert an element to a specified position, for example, index number1Location:

1 >>> classmates.insert(1, 'Jack')2 >>> classmates3 ['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

To delete the element at the end of the list, usepop()Method:

1 >>> classmates.pop()2 'Adam'3 >>> classmates4 ['Michael', 'Jack', 'Bob', 'Tracy']

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

1 >>> classmates.pop(1)2 'Jack'3 >>> classmates4 ['Michael', 'Bob', 'Tracy']

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

1 >>> classmates[1] = 'Sarah'2 >>> classmates3 ['Michael', 'Sarah', 'Tracy']

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

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

The list element can also be another list, for example:

1 >>> s = ['python', 'java', ['asp', 'php'], 'scheme']2 >>> len(s)3 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:

1 >>> p = ['asp', 'php']2 >>> s = ['python', 'java', p, 'scheme']

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:

1 >>> L = []2 >>> len(L)3 0
Tuple

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:

1 >>> classmates = ('Michael', 'Bob', 'Tracy')

Now, the tuple of classmates cannot be changed, and it does not have methods such as append () and insert. Other methods for retrieving elements are the same as those for listing, which can be used normally.classmates[0],classmates[-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:

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

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

1 >>> t = ()2 >>> t3 ()

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

1 >>> t = (1)2 >>> t3 1

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:

1 >>> t = (1,)2 >>> t3 (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:

1 >>> t = ('a', 'b', ['A', 'B'])2 >>> t[2][0] = 'X'3 >>> t[2][1] = 'Y'4 >>> t5 ('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 to which tuple points at the beginning is not changed to another list. Therefore, tuple's so-called "unchanged" means that every element of tuple will always point to it. 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.

 

List and tuple are Python's built-in ordered sets. They are a variable and an immutable set. 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.