5. Data Structures

This chapter describes some things you've learned about already in more detail, and adds some new things as well.

5.1. More on Lists

The list data type has some more methods. Here are all of the methods of list objects:

list.append(x)

Add an item to the end of the list. Equivalent to a[len(a):] = [x].

list.extend(iterable)

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)

Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.clear()

Remove all items from the list. Equivalent to del a[:].

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

list.count(x)

Return the number of times x appears in the list.

list.sort(key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse()

Reverse the elements of the list in place.

list.copy()

Return a shallow copy of the list. Equivalent to a[:].

An example that uses most of the list methods:

>>> 水果 = ['橙', '苹果', '梨', '香蕉', '猕猴桃', '苹果', '香蕉']
>>> 水果.count('苹果')
2
>>> 水果.count('柑橘')
0
>>> 水果.index('香蕉')
3
>>> 水果.index('香蕉', 4)  # 从位置4开始搜索下一个香蕉
6
>>> 水果.reverse()
>>> 水果
['香蕉', '苹果', '猕猴桃', '香蕉', '梨', '苹果', '橙']
>>> 水果.append('葡萄')
>>> 水果
['香蕉', '苹果', '猕猴桃', '香蕉', '梨', '苹果', '橙', '葡萄']
>>> 水果.sort()  # 按照编码排序, 详见5.8
>>> 水果
['梨', '橙', '猕猴桃', '苹果', '苹果', '葡萄', '香蕉', '香蕉']
>>> 水果.pop()
'梨'

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed -- they return the default None. [1] This is a design principle for all mutable data structures in Python.

5.1.1. Using Lists as Stacks

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved ("last-in, first-out"). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:

>>>  = [3, 4, 5]
>>> .append(6)
>>> .append(7)
>>> 
[3, 4, 5, 6, 7]
>>> .pop()
7
>>> 
[3, 4, 5, 6]
>>> .pop()
6
>>> .pop()
5
>>> 
[3, 4]

5.1.2. Using Lists as Queues

It is also possible to use a list as a queue, where the first element added is the first element retrieved ("first-in, first-out"); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

>>> from collections import deque
>>> 队列 = deque(["张三", "李四", "王五"])
>>> 队列.append("小红")           # 小红来了
>>> 队列.append("小吴")          # 小吴来了
>>> 队列.popleft()                 # 最先到的离开了
'张三'
>>> 队列.popleft()                 # 第二个到的离开了
'李四'
>>> 队列                           # 按照到达顺序的剩余队列
deque(['王五', '小红', '小吴'])

5.1.3. List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

>>> 平方数 = []
>>> for  in range(10):
...     平方数.append(**2)
...
>>> 平方数
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:

平方数 = list(map(lambda : **2, range(10)))

or, equivalently:

平方数 = [**2 for  in range(10)]

which is more concise and readable.

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

>>> [(, ) for  in [1,2,3] for  in [3,1,4] if  != ]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it's equivalent to:

>>> 组合 = []
>>> for  in [1,2,3]:
...     for  in [3,1,4]:
...         if  != :
...             组合.append((, ))
...
>>> 组合
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the for and if statements is the same in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.

>>> 数组 = [-4, -2, 0, 2, 4]
>>> # 按每个值翻倍创建新列表
>>> [*2 for  in 数组]
[-8, -4, 0, 4, 8]
>>> # 过滤列表, 除去负数
>>> [ for  in 数组 if  >= 0]
[0, 2, 4]
>>> # 对所有元素应用一个函数
>>> [abs() for  in 数组]
[4, 2, 0, 2, 4]
>>> # 对每个元素调用一个方法
>>> 新鲜水果 = ['  香蕉', '  罗甘莓 ', '百香果  ']
>>> [武器.strip() for 武器 in 新鲜水果]
['香蕉', '罗甘莓', '百香果']
>>> # 创建(数, 平方数)的二元组列表
>>> [(, **2) for  in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # 元组必须在括号内, 否则报错
>>> [, **2 for  in range(6)]
  File "<stdin>", line 1, in <module>
    [数, 数**2 for 数 in range(6)]
               ^
SyntaxError: invalid syntax
>>> # 用两个'for'的listcomp展开列表
>>> 数组 = [[1,2,3], [4,5,6], [7,8,9]]
>>> [ for 元素 in 数组 for  in 元素]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can contain complex expressions and nested functions:

>>> from math import pi
>>> [str(round(pi, 小数位)) for 小数位 in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

5.1.4. Nested List Comprehensions

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

>>> 矩阵 = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

The following list comprehension will transpose rows and columns:

>>> [[[列数] for  in 矩阵] for 列数 in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalent to:

>>> 转置矩阵 = []
>>> for 列数 in range(4):
...     转置矩阵.append([[列数] for  in 矩阵])
...
>>> 转置矩阵
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

which, in turn, is the same as:

>>> 转置矩阵 = []
>>> for 列数 in range(4):
...     # 下面三行实现嵌套的listcomp
...     转置行 = []
...     for  in 矩阵:
...         转置行.append([列数])
...     转置矩阵.append(转置行)
...
>>> 转置矩阵
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

>>> list(zip(*矩阵))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

See Unpacking Argument Lists for details on the asterisk in this line.

5.2. The del statement

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:

>>>  = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del [0]
>>> 
[1, 66.25, 333, 333, 1234.5]
>>> del [2:4]
>>> 
[1, 66.25, 1234.5]
>>> del [:]
>>> 
[]

del can also be used to delete entire variables:

>>> del 

Referencing the name a hereafter is an error (at least until another value is assigned to it). We'll find other uses for del later.

5.3. Tuples and Sequences

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types --- list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

>>> 元组 = 12345, 54321, '你好!'
>>> 元组[0]
12345
>>> 元组
(12345, 54321, '你好!')
>>> # 元组可以嵌套:
... 嵌套元组 = 元组, (1, 2, 3, 4, 5)
>>> 嵌套元组
((12345, 54321, '你好!'), (1, 2, 3, 4, 5))
>>> # 元组不可修改:
... 元组[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # 但他们可以包含可修改的对象:
... 可改元组 = ([1, 2, 3], [3, 2, 1])
>>> 可改元组
([1, 2, 3], [3, 2, 1])

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

>>>  = ()
>>> 单例 = '你好',    # <-- 注意最后的逗号
>>> len()
0
>>> len(单例)
1
>>> 单例
('你好',)

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

>>> 数1, 数2, 文本 = 元组

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

5.4. Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration:

>>> 果篮 = {'苹果', '橙', '苹果', '梨', '橙', '香蕉'}
>>> print(果篮)                      # 显示重复值已被除去
{'梨', '橙', '香蕉', '苹果'}
>>> '橙' in 果篮                 # 快速测试是否在集合中
True
>>> '茅草' in 果篮
False

>>> # 用两个短语中的字演示集合的操作
...
>>>  = set('一二一立定')
>>>  = set('一二三四')
>>>                                   # 甲中出现的字
{'一', '二', '定', '立'}
>>>  -                               # 在甲中但不在乙中的字
{'定', '立'}
>>>  |                               # 在甲或乙中的字
{'四', '三', '定', '一', '二', '立'}
>>>  &                               # 同时在甲和乙中的字
{'一', '二'}
>>>  ^                               # 在甲或乙中, 但不同时在甲和乙中的字
{'三', '定', '四', '立'}

Similarly to list comprehensions, set comprehensions are also supported:

>>> a = { for  in '一二一立定' if  not in '一二'}
>>> a
{'定', '立'}

5.5. Dictionaries

Another useful data type built into Python is the dictionary (see Mapping Types --- dict). Dictionaries are sometimes found in other languages as "associative memories" or "associative arrays". Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can't use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). [2] To check whether a single key is in the dictionary, use the in keyword.

Here is a small example using a dictionary:

>>> 电话簿 = {'张三': 1234, '李四': 4321}
>>> 电话簿['王五'] = 5678
>>> 电话簿
{'张三': 1234, '李四': 4321, '王五': 5678}
>>> 电话簿['张三']
1234
>>> del 电话簿['李四']
>>> 电话簿['小红'] = 5678
>>> 电话簿
{'张三': 1234, '王五': 5678, '小红': 5678}
>>> list(电话簿.keys())
['张三', '王五', '小红']
>>> sorted(电话簿.keys())
['小红', '张三', '王五']
>>> '王五' in 电话簿
True
>>> '张三' not in 电话簿
False

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>> {: **2 for  in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>> dict(李四=4321, 王五=5678, 张三=1234)
{'李四': 4321, '王五': 5678, '张三': 1234}

5.6. Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

>>> 人物 = {'唐僧': '人', '孙悟空': '猴'}
>>> for ,  in 人物.items():
...     print(, )
...
唐僧 人
孙悟空 猴

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>> for 索引,  in enumerate(['唐僧', '孙悟空', '猪八戒', '沙僧']):
...     print(索引, )
...
0 唐僧
1 孙悟空
2 猪八戒
3 沙僧

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>> 问题 = ['名字', '追求', '喜爱颜色']
>>> 答案 = ['玄奘', '真经', '无']
>>> for ,  in zip(问题, 答案):
...     print('你的{0}是什么?  是{1}.'.format(, ))
...
你的名字是什么?   是玄奘.
你的追求是什么?   是真经.
你的喜爱颜色是什么?   是无.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>> for 索引 in reversed(range(1, 10, 2)):
...     print(索引)
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>> 果篮 = ['苹果', '桔子', '苹果', '梨', '桔子', '香蕉']
>>> for 水果 in sorted(set(果篮)):
...     print(水果)
...
桔子

苹果
香蕉

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

>>> import math
>>> 原始数据 = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> 过滤后数据 = []
>>> for  in 原始数据:
...     if not math.isnan():
...         过滤后数据.append()
...
>>> 过滤后数据
[56.2, 51.7, 55.3, 52.5, 47.8]

5.7. More on Conditions

The conditions used in while and if statements can contain any operators, not just comparisons.

The comparison operators in and not in check whether a value occurs (does not occur) in a sequence. The operators is and is not compare whether two objects are really the same object; this only matters for mutable objects like lists. All comparison operators have the same priority, which is lower than that of all numerical operators.

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c.

Comparisons may be combined using the Boolean operators and and or, and the outcome of a comparison (or of any other Boolean expression) may be negated with not. These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C. As always, parentheses can be used to express the desired composition.

The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,

>>> 字符串1, 字符串2, 字符串3 = '', '混沌', '盘古'
>>> 非空 = 字符串1 or 字符串2 or 字符串3
>>> 非空
'混沌'

Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.

5.8. Comparing Sequences and Other Types

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python' < '易语言'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
'苹果'                  < '香蕉'   # 由于汉字编码. ord('苹') = 33529, ord('香') = 39321

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.

Footnotes

[1]Other languages may return the mutated object, which allows method chaining, such as d->insert("a")->remove("b")->sort();.
[2]Calling d.keys() will return a dictionary view object. It supports operations like membership test and iteration, but its contents are not independent of the original dictionary -- it is only a view.