Python practical notes (2) list and tuple

list

This is a list :

classmates = ['Michael', 'Bob', 'Tracy'] //内部数据类型可以不同

The same len() function can get the length:

len(classmates)

Take out the list contents:

classmates[0]

classmates[-1]

Append elements at the end of the list:

classmates.append('Adam')

Insert the specified position:

classmates.insert(1, 'Jack')

Remove elements from the end of a list:

classmates.pop()// can specify the locationclassmates.pop(i)

To replace an element with another element

classmates[1] = 'Sarah'

A list element can also be another list

>>> s = ['python', 'java', ['asp', 'php'], 'scheme'] >>> len(s) 4 

Note that sthere are only 4 elements, of which s[2]is another list, which is easier to understand if you split it up:

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

To get it, it can 'php'be written p[1]or s[2][1], so it scan be regarded as a two-dimensional array, similar to three-dimensional, four-dimensional... arrays, but it is rarely used.

If there is no element in a list, it is an empty list, and its length is 0:

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

tuple

Tuples are similar to lists, but immutable, so the code is safer

Special attention is needed when the tuple locates only one element: add, disambiguate

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

This is a mutable tuple

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

In fact, the list is changed, and the invariant of tuple is that "pointing to the same" still points to that list

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325272886&siteId=291194637