Python3 Data Structures
In this chapter we introduce Python data structures, drawing on the knowledge covered earlier.
List
Lists in Python are mutable, which is the most important difference from strings and tuples: in short, lists can be modified while strings and tuples cannot.
The following are methods of Python lists:
| Method | Description |
|---|---|
| list.append(x) | Add an element to the end of the list, equivalent to a[len(a):] = [x]. |
| list.extend(L) | Extend the list by adding all elements of a specified list, equivalent to a[len(a):] = L. |
| list.insert(i, x) | Insert an element at a specified position. The first parameter is the index of the element before which it is inserted; for example a.insert(0, x) inserts at the very beginning of the list, and a.insert(len(a), x) is equivalent to a.append(x). |
| list.remove(x) | Remove the first element in the list whose value is x. If no such element exists, an error is returned. |
| list.pop([i]) | Remove the element at the specified position in the list and return it. If no index is given, a.pop() returns the last element. The element is then removed from the list. (The square brackets around i in the method indicate that the parameter is optional, not that you should type a pair of brackets; you will often encounter this notation in the Python library reference.) |
| list.clear() | Remove all items from the list, equivalent to del a[:]. |
| list.index(x) | Return the index of the first element in the list whose value is x. If no element matches, an error is returned. |
| list.count(x) | Return the number of times x appears in the list. |
| list.sort() | Sort the elements in the list. |
| list.reverse() | Reverse the elements in the list. |
| list.copy() | Return a shallow copy of the list, equivalent to a[:]. |
The following example demonstrates most of the list methods:
Example
a
=
[
66.25
,
333
,
333
,
1
,
1234.5
]
(
a.
count
(
333
)
,
a.
count
(
66.25
)
,
a.
count
(
'x'
)
)
2
1
0
a.
insert
(
2
,
1
)
a.
append
(
333
)
a
[
66.25
,
333
,
1
,
333
,
1
,
1234.5
,
333
]
a.
index
(
333
)
1
a.
remove
(
333
)
a
[
66.25
,
1
,
333
,
1
,
1234.5
,
333
]
a.
reverse
(
)
a
[
333
,
1234.5
,
1
,
333
,
1
,
66.25
]
a.
sort
(
)
a
[
1
,
1
,
66.25
,
333
,
333
,
1234.5
]
Note: methods that modify the list, such as insert, remove, or sort, have no return value.
Using a list as a stack
In Python, a list can be used to implement a stack. A stack is a Last-In-First-Out (LIFO) data structure, meaning the last element added is the first one removed. Lists provide methods that make them well suited to stack operations, especially append() and pop() method.
The append() method adds an element to the top of the stack, and pop() without an index releases an element from the top of the stack.
Stack operations
- Push: add an element to the top of the stack.
- Pop: remove and return the top element of the stack.
- View the top element (Peek/Top): return the top element without removing it.
- Check whether it is empty (IsEmpty): Check whether the stack is empty.
- Get the stack size (Size): get the number of elements in the stack.
Below is a detailed explanation of how to implement these operations using lists in Python:
1. Create an empty stack
Example
stack
=
[
]
2. Push operation
Use the append() method to add an element to the top of the stack:
Example
stack.
append
(
1
)
stack.
append
(
2
)
stack.
append
(
3
)
(
stack
)
Output: [1, 2, 3]
3. Pop operation
Use the pop() method to remove and return the top element of the stack:
Example
top_element
=
stack.
pop
(
)
(
top_element
)
Output: 3
(
stack
)
Output: [1, 2]
4. View the top element (Peek/Top)
Access the last element of the list directly (without removing it):
Example
top_element
=
stack
[
1
]
(
top_element
)
Output: 2
5. Check whether it is empty (IsEmpty)
Check whether the list is empty:
Example
is_empty
=
len
(
stack
)
==
0
(
is_empty
)
Output: False
6. Get the stack size (Size)
Use the len() function to get the number of elements in the stack:
Example
size
=
len
(
stack
)
(
size
)
Output: 2
Example
Below is a complete example showing how to use the operations above to implement a simple stack:
Example
class
Stack:
def
init
(
self
)
:
self
.
stack
=
[
]
def
push
(
self
,
item
)
:
self
.
stack
.
append
(
item
)
def
pop
(
self
)
:
if
not
self
.
is_empty
(
)
:
return
self
.
stack
.
pop
(
)
else
:
raise
IndexError
(
"pop from empty stack"
)
def
peek
(
self
)
:
if
not
self
.
is_empty
(
)
:
return
self
.
stack
[
1
]
else
:
raise
IndexError
(
"peek from empty stack"
)
def
is_empty
(
self
)
:
return
len
(
self
.
stack
)
==
0
def
size
(
self
)
:
return
len
(
self
.
stack
)
Usage examples
stack
=
Stack
(
)
stack.
push
(
1
)
stack.
push
(
2
)
stack.
push
(
3
)
(
"Top element:"
,
stack.
peek
(
)
)
Output: Top element: 3
(
"Stack size:"
,
stack.
size
(
)
)
Output: Stack size: 3
(
"Popped element:"
,
stack.
pop
(
)
)
Output: Popped element: 3
(
"Is the stack empty:"
,
stack.
is_empty
(
)
)
Output: Is the stack empty: False
(
"Stack size:"
,
stack.
size
(
)
)
Output: Stack size: 2
In the code above, we defined a Stack class that wraps a list as the underlying data structure and implements the basic stack operations.
The output is as follows:
栈顶元素: 3
栈大小: 3
弹出元素: 3
栈是否为空: False
栈大小: 2
Using a list as a queue
In Python, a list can be used as a queue, but because of how lists work, using a list directly to implement a queue is not the best choice.
A queue is a First-In-First-Out (FIFO) data structure, meaning the earliest element added is the first one removed.
With lists, frequently inserting or deleting elements at the beginning hurts performance, because those operations have time complexity O(n). To solve this, Python provides collections.deque, a double-ended queue that can add and remove elements efficiently at both ends.
Implementing a queue with collections.deque
collections.deque is part of the Python standard library and is very well suited to implementing queues.
Below is an example of implementing a queue with deque:
Example
from
collections
import
deque
Create an empty queue
queue
=
deque
(
)
Add elements to the tail of the queue
queue.
append
(
'a'
)
queue.
append
(
'b'
)
queue.
append
(
'c'
)
(
"Queue state:"
,
queue
)
Output: Queue state: deque(['a', 'b', 'c'])
Remove an element from the head of the queue
first_element
=
queue.
popleft
(
)
(
"Removed element:"
,
first_element
)
Output: Removed element: a
(
"Queue state:"
,
queue
)
Output: Queue state: deque(['b', 'c'])
View the head element (without removing it)
front_element
=
queue
[
0
]
(
"Head element:"
,
front_element
)
Output: Head element: b
Check whether the queue is empty
is_empty
=
len
(
queue
)
==
0
(
"Is the queue empty:"
,
is_empty
)
Output: Is the queue empty: False
Get the queue size
size
=
len
(
queue
)
(
"Queue size:"
,
size
)
Output: Queue size: 2
### 使用列表实现队列
Although deque is more efficient, if you insist on using a list to implement a queue, you can do it this way. Here is an example of how to implement a queue using a list:
1. Create queue
## 实例
queue
=
[
]
2. Add element to the end of the queue
# Use the append() method to add elements to the end of the queue:
## 实例
queue.
append
(
'a'
)
queue.
append
(
'b'
)
queue.
append
(
'c'
)
print
(
"队列状态:"
,
queue
)
# Output: Queue status: ['a', 'b', 'c']
3. Remove element from the front of the queue
// Remove element from the front of the queue using pop(0):
## 实例
first_element
=
queue.
pop
(
0
)
print
(
"移除的元素:"
,
first_element
)
# Output: Removed element: a
print
(
"队列状态:"
,
queue
)
# Output: Queue status: ['b', 'c']
4. View the front element (without removing)
Directly access the first element of the list:
## 实例
front_element
=
queue
[
0
]
print
(
"队首元素:"
,
front_element
)
# Output: First element: b
**5. Check if the queue is empty**
Check if the list is empty:
## 实例
is_empty
=
len
(
queue
)
==
0
print
(
"队列是否为空:"
,
is_empty
)
# Output: Is the queue empty: False
# Get queue size
# Get the size of the queue using the len() function:
## 实例
size
=
len
(
queue
)
print
(
"队列大小:"
,
size
)
# Output: Queue size: 2
### 实例(使用列表实现队列)
## 实例
class
Queue
:
def
__init__
(
self
)
:
self
.
queue
=
[
]
def
enqueue
(
self
,
item
)
:
self
.
queue
.
append
(
item
)
def
dequeue
(
self
)
:
if
not
self
.
is_empty
(
)
:
return
self
.
queue
.
pop
(
0
)
else
:
raise
IndexError
(
"dequeue from empty queue"
)
def
peek
(
self
)
:
if
not
self
.
is_empty
(
)
:
return
self
.
queue
[
0
]
else
:
raise
IndexError
(
"peek from empty queue"
)
def
is_empty
(
self
)
:
return
len
(
self
.
queue
)
==
0
def
size
(
self
)
:
return
len
(
self
.
queue
)
# Usage example
queue
=
Queue
(
)
queue.
enqueue
(
'a'
)
queue.
enqueue
(
'b'
)
queue.
enqueue
(
'c'
)
print
(
"队首元素:"
,
queue.
peek
(
)
)
# Output: First element: a
print
(
"队列大小:"
,
queue.
size
(
)
)
# Output: Queue size: 3
print
(
"移除的元素:"
,
queue.
dequeue
(
)
)
# Output: Removed element: a
print
(
"队列是否为空:"
,
queue.
is_empty
(
)
)
# Output: Is the queue empty: False
print
(
"队列大小:"
,
queue.
size
(
)
)
# Output: Queue size: 2
虽然可以使用列表来实现队列,但使用 collections.deque 会更高效和简洁。它提供了 O(1) 时间复杂度的添加和删除操作,非常适合队列这种数据结构。
---
## 列表推导式
列表推导式提供了从序列创建列表的简单途径。通常应用程序将一些操作应用于某个序列的每个元素,用其获得的结果作为生成新列表的元素,或者根据确定的判定条件创建子序列。
每个列表推导式都在 for 之后跟一个表达式,然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。如果希望表达式推导出一个元组,就必须使用括号。
# Here we multiply each value in the list by three to get a new list:
>>>
vec
=
[
2
,
4
,
6
]
>>>
[
3
*x
for
x
in
vec
]
[
6
,
12
,
18
]
Now let's play a little variation:
>>>
[
[
x
,
x**
2
]
for
x
in
vec
]
[
[
2
,
4
]
,
[
4
,
16
]
,
[
6
,
36
]
]
Here we call a certain method for each element in the sequence:
## 实例
>>>
freshfruit
=
[
' banana'
,
' loganberry '
,
'passion fruit '
]
>>>
[
weapon.
strip
(
)
for
weapon
in
freshfruit
]
[
'banana'
,
'loganberry'
,
'passion fruit'
]
We can use an if clause as a filter:
>>>
[
3
*x
for
x
in
vec
if
x
>
3
]
[
12
,
18
]
>>>
[
3
*x
for
x
in
vec
if
x
<
2
]
[
]
以下是一些关于循环和其它技巧的演示:
>>>
vec1
=
[
2
,
4
,
6
]
>>>
vec2
=
[
4
,
3
,
-
9
]
>>>
[
x*y
for
x
in
vec1
for
y
in
vec2
]
[
8
,
6
,
-
18
,
16
,
12
,
-
36
,
24
,
18
,
-
54
]
>>>
[
x+y
for
x
in
vec1
for
y
in
vec2
]
[
6
,
5
,
-
7
,
8
,
7
,
-
5
,
10
,
9
,
-
3
]
>>>
[
vec1
[
i
]
*vec2
[
i
]
for
i
in
range
(
len
(
vec1
)
)
]
[
8
,
12
,
-
54
]
List comprehensions can use complex expressions or nested functions:
>>>
[
str
(
round
(
355
/
113
,
i
)
)
for
i
in
range
(
1
,
6
)
]
[
'3.1'
,
'3.14'
,
'3.142'
,
'3.1416'
,
'3.14159'
]
---
## Nested list parsing
Python的列表还可以嵌套。
The following example shows a list of 3x4 matrices:
>>>
matrix
=
[
...
[
1
,
2
,
3
,
4
]
,
...
[
5
,
6
,
7
,
8
]
,
...
[
9
,
10
,
11
,
12
]
,
...
]
The following example converts a list of 3x4 matrices to a 4x3 list:
>>>
[
[
row
[
i
]
for
row
in
matrix
]
for
i
in
range
(
4
)
]
[
[
1
,
5
,
9
]
,
[
2
,
6
,
10
]
,
[
3
,
7
,
11
]
,
[
4
,
8
,
12
]
]
The above examples can also be implemented using the following methods:
>>>
transposed
=
[
]
>>>
for
i
in
range
(
4
)
:
...
transposed
.
append
(
[
row
[
i
]
for
row
in
matrix
]
)
...
>>>
transposed
[
[
1
,
5
,
9
]
,
[
2
,
6
,
10
]
,
[
3
,
7
,
11
]
,
[
4
,
8
,
12
]
]
Another implementation method:
>>>
transposed
=
[
]
>>>
for
i
in
range
(
4
)
:
...
# the following 3 lines implement the nested listcomp
...
transposed_row
=
[
]
...
for
row
in
matrix:
...
transposed_row
.
append
(
row
[
i
]
)
...
transposed
.
append
(
transposed_row
)
...
>>>
transposed
[
[
1
,
5
,
9
]
,
[
2
,
6
,
10
]
,
[
3
,
7
,
11
]
,
[
4
,
8
,
12
]
]
---
## del 语句
The del statement can delete an element from a list based on its index, rather than by its value. This is different from using pop(), which returns a value. The del statement can delete a slice from a list, or clear the entire list (the method we introduced previously was to assign an empty list to that slice). For example:
>>>
a
=
[
-
1
,
1
,
66.25
,
333
,
333
,
1234.5
]
>>>
del
a
[
0
]
>>>
a
[
1
,
66.25
,
333
,
333
,
1234.5
]
>>>
del
a
[
2
:
4
]
>>>
a
[
1
,
66.25
,
1234.5
]
>>>
del
a
[
:
]
>>>
a
[
]
You can also use del to delete entity variables:
del a
---
## Tuples and Sequences
A tuple is composed of several comma-separated values, for example:
>>>
t
=
12345
,
54321
,
'hello!'
>>>
t
[
0
]
12345
>>>
t
(
12345
,
54321
,
'hello!'
)
>>>
# Tuples may be nested:
...
u
=
t
,
(
1
,
2
,
3
,
4
,
5
)
>>>
u
(
(
12345
,
54321
,
'hello!'
)
,
(
1
,
2
,
3
,
4
,
5
)
)
如你所见,元组在输出时总是有括号的,以便于正确表达嵌套结构。在输入时可能有或没有括号, 不过括号通常是必须的(如果元组是更大的表达式的一部分)。
---
## 集合
集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。
可以用大括号({})创建集合。注意:如果要创建一个空集合,你必须用 set() 而不是 {} ;后者创建一个空的字典,下一节我们会介绍这个数据结构。
Here is a simple demonstration:
>>>
basket
=
{
'apple'
,
'orange'
,
'apple'
,
'pear'
,
'orange'
,
'banana'
}
>>>
print
(
basket
)
# Remove duplicates
{
'orange'
,
'banana'
,
'pear'
,
'apple'
}
>>>
'orange'
in
basket
# Check members
True
>>>
'crabgrass'
in
basket
False
>>>
# This demonstrates two set operations
...
>>>
a
=
set
(
'abracadabra'
)
>>>
b
=
set
(
'alacazam'
)
>>>
a
# the only letter in a
{
'a'
,
'r'
,
'b'
,
'c'
,
'd'
}
>>>
a - b
# letters in a but not in b
{
'r'
,
'd'
,
'b'
}
>>>
a | b
# letters in a or b
{
'a'
,
'c'
,
'r'
,
'd'
,
'b'
,
'm'
,
'z'
,
'l'
}
>>>
a & b
# letters common to both a and b
{
'a'
,
'c'
}
>>>
a ^ b
# letters in a or b, but not in both a and b
{
'r'
,
'd'
,
'b'
,
'm'
,
'z'
,
'l'
}
Sets also support comprehensions:
>>>
a
=
{
x
for
x
in
'abracadabra'
if
x
not
in
'abc'
}
>>>
a
{
'r'
,
'd'
}
---
## 字典
另一个非常有用的 Python 内建数据类型是字典。
序列是以连续的整数为索引,与此不同的是,字典以关键字为索引,关键字可以是任意不可变类型,通常用字符串或数值。
理解字典的最佳方式是把它看做无序的键=>值对集合。在同一个字典之内,关键字必须是互不相同。
一对大括号创建一个空的字典:{}。
This is a simple example of dictionary usage:
>>>
tel
=
{
'jack'
:
4098
,
'sape'
:
4139
}
>>>
tel
[
'guido'
]
=
4127
>>>
tel
{
'sape'
:
4139
,
'guido'
:
4127
,
'jack'
:
4098
}
>>>
tel
[
'jack'
]
4098
>>>
del
tel
[
'sape'
]
>>>
tel
[
'irv'
]
=
4127
>>>
tel
{
'guido'
:
4127
,
'irv'
:
4127
,
'jack'
:
4098
}
>>>
list
(
tel.
keys
(
)
)
[
'irv'
,
'guido'
,
'jack'
]
>>>
sorted
(
tel.
keys
(
)
)
[
'guido'
,
'irv'
,
'jack'
]
>>>
'guido'
in
tel
True
>>>
'jack'
not
in
tel
False
The dict() constructor builds a dictionary directly from a list of key-value tuples. If there is a fixed pattern, a list comprehension specifies the specific key-value pairs:
>>>
dict
(
[
(
'sape'
,
4139
)
,
(
'guido'
,
4127
)
,
(
'jack'
,
4098
)
]
)
{
'sape'
:
4139
,
'jack'
:
4098
,
'guido'
:
4127
}
In addition, dictionary comprehension can be used to create expression dictionaries with arbitrary keys and values:
>>>
{
x: x**
2
for
x
in
(
2
,
4
,
6
)
}
{
2
:
4
,
4
:
16
,
6
:
36
}
If the keywords are just simple strings, it is sometimes more convenient to specify key-value pairs using keyword arguments:
>>>
dict
(
sape
=
4139
,
guido
=
4127
,
jack
=
4098
)
{
'sape'
:
4139
,
'jack'
:
4098
,
'guido'
:
4127
}
---
## Traversal Techniques
When iterating over a dictionary, the keys and corresponding values can be retrieved simultaneously using the items() method:
>>>
knights
=
{
'gallahad'
:
'the pure'
,
'robin'
:
'the brave'
}
>>>
for
k
,
v
in
knights.
items
(
)
:
...
print
(
k
,
v
)
...
gallahad
the pure
robin the brave
When iterating over a sequence, the index position and the corresponding value can be obtained simultaneously using the enumerate() function:
>>>
for
i
,
v
in
enumerate
(
[
'tic'
,
'tac'
,
'toe'
]
)
:
...
print
(
i
,
v
)
...
0
tic
1
tac
2
toe
To iterate over two or more sequences simultaneously, you can use the zip() function:
>>>
questions
=
[
'name'
,
'quest'
,
'favorite color'
]
>>>
answers
=
[
'lancelot'
,
'the holy grail'
,
'blue'
]
>>>
for
q
,
a
in
zip
(
questions
,
answers
)
:
...
print
(
'What is your {0}? It is {1}.'
.
format
(
q
,
a
)
)
...
What
is
your name? It
is
lancelot.
What
is
your quest? It
is
the holy grail.
What
is
your favorite color? It
is
blue.
To iterate over a sequence in reverse, first specify the sequence, then call the reversed() function:
>>>
for
i
in
reversed
(
range
(
1
,
10
,
2
)
)
:
...
print
(
i
)
...
9
7
5
3
1
To iterate over a sequence in order, use the sorted() function to return a sorted sequence without modifying the original value:
>>>
basket
=
[
'apple'
,
'orange'
,
'apple'
,
'pear'
,
'orange'
,
'banana'
]
>>>
for
f
in
sorted
(
set
(
basket
)
)
:
...
print
(
f
)
...
apple
banana
orange
pear
---
## Reference Documentation
- [Python3 列表](/python3/python3-list.html)
- [Python3 元组](/python3/python3-tuple.html)
- [Python3 字典](/python3/python3-dictionary.html)