8.2. Python列表再探¶
8.2. Python Lists Revisited
在第2章算法分析中,我们介绍了 Python 列表数据类型的一些 Big-O 性能限制。然而,我们当时还没有足够的知识来理解 Python 是如何实现其列表数据类型的。在第基本数据结构章中,你学习了如何使用节点和引用模式来实现一个链表。然而,这种节点和引用的实现仍然无法匹配 Python 列表的性能。在本节中,我们将探讨 Python 列表实现的原理。需要注意的是,这种实现不会与 Python 的实际实现完全相同,因为 Python 列表是用 C 语言实现的。本节的目的是使用 Python 演示关键概念,而不是替代 C 语言实现。
Python 列表实现的关键在于使用一种叫做 数组 的数据类型,这种类型在 C、C++、Java 和许多其他编程语言中都很常见。数组非常简单,只能存储一种类型的数据。例如,你可以有一个整数数组或浮点数数组,但不能在一个数组中混合这两种类型。数组只支持两种操作:索引和赋值到数组索引。
最好的理解数组的方式是把它看作计算机内存中的一个连续字节块。这个块被分割成 图 1
展示了一个大小为可以容纳六个浮点值的数组。

在 Python 中,每个浮点数使用 16 1 字节的内存。因此,图 1
中的数组总共使用了 96 2 字节。基地址是数组在内存中开始的位置。你之前见过 Python 中不同对象的地址。例如: <__main__.Foo object at 0x5eca30>
表示对象 Foo
存储在内存地址 0x5eca30
。地址非常重要,因为数组通过一个非常简单的计算实现索引操作:
item_address = base_address + index * size_of_object
例如,假设我们的数组起始位置是 0x000040
,即十进制的 64。要计算数组中位置 4 的对象位置,我们只需进行算术运算:
Python 用于实现链表的数组策略如下:
- Python 使用一个数组来存储对其他对象的引用(在 C 语言中称为 指针)。
- Python 使用一种叫做 超额分配 的策略来分配一个比初始所需空间更多的数组。
- 当初始数组填满后,会超额分配一个更大的数组,并将旧数组的内容复制到新数组中。
这一策略的影响非常惊人。让我们先了解这些影响,然后再深入到实现或证明细节中。
- 访问特定位置的项是
。 - 向列表中追加元素在平均情况下是
,但在最坏情况下是 。 - 从列表末尾弹出元素是
。 - 从列表中删除项是
。 - 在任意位置插入项是
。
让我们看一下上述策略如何在一个非常简单的实现中工作。首先,我们将仅实现构造函数、__resize
方法和 append
方法。我们将这个类称为 ArrayList
。在构造函数中,我们需要初始化两个实例变量。第一个变量用于跟踪当前数组的大小,我们称之为 max_size
。第二个实例变量用于跟踪列表的当前末尾,我们称之为 last_index
。由于 Python 没有数组数据类型,我们将使用列表来模拟数组。Listing [lst_arraylistinit]
包含 ArrayList
的前三个方法的代码。注意,构造函数初始化了上述两个实例变量,然后创建了一个称为 my_array
的零元素数组。构造函数还创建了一个名为 size_exponent
的实例变量。我们将很快理解这个变量的用途。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
接下来,我们将实现 append
方法。append
方法的第一步是检查 last_index
是否大于数组中可用索引位置的数量(第 9
行)。如果是这种情况,则调用 __resize
。注意,我们使用双下划线约定将 resize
方法设置为私有。数组大小调整后,将新值添加到列表中的 last_index
位置,并将 last_index
增加 1。
resize
方法使用 19
行开始的循环中完成。最后,必须更新 max_size
和 last_index
的值,size_exponent
必须增加,并将 new_array
保存为 self.my_array
。在 C 语言中,self.my_array
旧的内存块会被显式地返回给系统以供重用。然而,请记住,在 Python 中,未被引用的对象会被垃圾回收算法自动清理。
在继续之前,让我们分析一下为什么这种策略为 append
操作提供了平均 last_index
是 2 的幂时,此时追加一个项的成本是
由于复制 last_index
项的昂贵操作发生的频率相对较低,我们将成本分摊,或称为 摊销,将插入的成本分摊到所有的追加操作上。当我们这样做时,任何一次插入的平均成本为
上面的求和可能对你来说不太明显,因此我们可以再深入思考一下。求和从零到
接下来,我们来看看索引操作符。Listing [lst_arrindex]
展示了我们对数组位置的索引和赋值的 Python 实现。回顾一下,我们之前讨论过,找到数组中第 listobject.c
文件。
def __getitem__(self, idx):
if idx < self.last_index:
return self.my_array[idx]
raise LookupError("index out of bounds")
def __setitem__(self, idx, val):
if idx < self.last_index:
self.my_array[idx] = val
raise LookupError("index out of bounds")
最后,让我们看看其中一种成本较高的列表操作:插入。当我们将一个项插入 ArrayList
时,我们需要首先将插入点及其之后的所有内容向前移动一个索引位置,以为插入的项腾出空间。这个过程在 Figure 2
中进行了说明。

正确实现 insert
的关键是意识到在数组中移动值时不想覆盖任何重要数据。实现这一点的方法是从列表的末尾向插入点方向移动,向前复制数据。我们的 insert
实现如下 Listing [lst_arrlistins]
。注意第 4
行的 range
设置,以确保我们首先将现有数据复制到数组的未使用部分,然后将随后的值复制到已经移动的旧值上。如果循环从插入点开始,将该值复制到数组中下一个较大的索引位置,旧值将永远丢失。
1 2 3 4 5 6 7 |
|
插入操作的性能是
我们还有一些其他有趣的操作没有为 ArrayList
实现,包括:pop
、del
、index
,以及使 ArrayList
可迭代。我们将这些改进留给你作为练习。
In Chapter analysis we introduced some Big-O performance limits on Python’s list data type. However, we did not yet have the knowledge necessary to understand how Python implements its list data type. in Chapter basic-data-structures you learned how to implement a linked list using the nodes and references pattern. However, the nodes and references implementation still did not match the performance of the Python list. In this section we will look at the principles behind the Python list implementation. It is important to recognize that this implementation is not going to be the same as Python’s since the real Python list is implemented in the C programming language. The idea in this section is to use Python to demonstrate the key ideas, not to replace the C implementation.
The key to Python’s implementation of a list is to use a data type called an array common to C, C++, Java, and many other programming languages. The array is very simple and is only capable of storing one kind of data. For example, you could have an array of integers or an array of floating point numbers, but you cannot mix the two in a single array. The array only supports two operations: indexing and assignment to an array index.
The best way to think about an array is that it is one continuous block of bytes in the computer’s memory. This block is divided up into Figure 1
illustrates the idea of an array that is sized to hold six floating point values.

In Python, each floating point number uses 16 1 bytes of memory. So the array in Figure 1
uses a total of 96 2 bytes. The base address is the location in memory where the array starts. You have seen addresses before in Python for different objects that you have defined. For example: <__main__.Foo object at 0x5eca30>
shows that the object Foo
is stored at memory address 0x5eca30
. The address is very important because an array implements the index operator using a very simple calculation:
item_address = base_address + index * size_of_object
For example, suppose that our array starts at location 0x000040
, which is 64 in decimal. To calculate the location of the object at position 4 in the array we simply do the arithmetic:
The general strategy that Python uses to implement a linked list using an array is as follows:
-
Python uses an array that holds references (called pointers in C) to other objects.
-
Python uses a strategy called over-allocation to allocate an array with space for more objects than is needed initially.
-
When the initial array is finally filled up, a new, bigger array is over-allocated and the contents of the old array are copied to the new array.
The implications of this strategy are pretty amazing. Let’s look at what they are first before we dive into the implementation or prove anything.
- Accessing an itema at a specific location is
. - Appending to the list is
on average, but in the worst case. - Popping from the end of the list is
. - Deleting an item from the list is
. - Inserting an item into an arbitrary position is
.
Let’s look at how the strategy outlined above works for a very simple implementation. To begin, we will only implement the constructor, a __resize
method, and the append
method. We will call this class ArrayList
. In the constructor we will need to initialize two instance variables. The first will keep track of the size of the current array; we will call this max_size
. The second instance variable will keep track of the current end of the list; we will call this one last_index
. Since Python does not have an array data type, we will use a list to simulate an array. Listing [lst_arraylistinit]
contains the code for the first three methods of ArrayList
. Notice that the constructor method initializes the two instance variables described above and then creates a zero element array called my_array
. The constructor also creates an instance variable called size_exponent
. We will understand how this variable is used shortly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Next, we will implement the append
method. The first thing append
does is test for the condition where last_index
is greater than the number of available index positions in the array (line [line:9]
). If this is the case then __resize
is called. Notice that we are using the double underscore convention to make the resize
method private. Once the array is resized the new value is added to the list at last_index
, and last_index
is incremented by one.
The resize
method calculates a new size for the array using [line:19]
. Finally the values max_size
and last_index
must be updated, size_exponent
must be incremented, and new_array
is saved as self.my_array
. In a language like C the old block of memory referenced by self.my_array
would be explicitly returned to the system for reuse. However, recall that in Python objects that are no longer referenced are automatically cleaned up by the garbage collection algorithm.
Before we move on let’s analyze why this strategy gives us an average append
. The key is to notice that most of the time the cost to append an item last_index
is a power of 2. When last_index
is a power of 2 then the cost to append an item is
Since the expensive cost of copying last_index
items occurs relatively infrequently we spread the cost out, or amortize, the cost of insertion over all of the appends. When we do this the cost of any one insertion averages out to
The summation in the previous equation may not be obvious to you, so let’s think about that a bit more. The sum goes from zero to
Next, let us turn to the index operators. Listing [lst_arrindex]
shows our Python implementation for index and assignment to an array location. Recall that we discussed above that the calculation required to find the memory location of the listobject.c
.
def __getitem__(self, idx):
if idx < self.last_index:
return self.my_array[idx]
raise LookupError("index out of bounds")
def __setitem__(self, idx, val):
if idx < self.last_index:
self.my_array[idx] = val
raise LookupError("index out of bounds")
Finally, let’s take a look at one of the more expensive list operations, insertion. When we insert an item into an ArrayList
we will need to first shift everything in the list at the insertion point and beyond ahead by one index position in order to make room for the item we are inserting. The process is illustrated in Figure 2
.

The key to implementing insert
correctly is to realize that as you
are shifting values in the array you do not want to overwrite any
important data. The way to do this is to work from the end of the list
back toward the insertion point, copying data forward. Our implementation
of insert
is shown in
Listing [lst_arrlistins]
. Note how the range
is
set up on
line [line:4]
to
ensure that we are copying existing data into the unused part of the
array first, and then subsequent values are copied over old values that
have already been shifted. If the loop had started at the insertion
point and copied that value to the next larger index position in the
array, the old value would have been lost forever.
1 2 3 4 5 6 7 |
|
The performance of the insert is
There are several other interesting operations that we have not yet implemented for our ArrayList
including: pop
, del
, index
, and making the ArrayList
iterable. We leave these enhancements to the ArrayList
as an exercise for you.
创建日期: 2024年9月9日