Python3 Data Structures
This chapter mainly introduces Python data structures in combination with the knowledge points learned earlier.
Python lists are mutable, which is the most important feature that distinguishes them from strings and tuples. In a nutshell: lists can be modified, while strings and tuples cannot.
The following are Python list methods:
| Method | Description |
|---|---|
| list.append(x) | Adds an element to the end of the list, equivalent to a[len(a):] = [x]. |
| list.extend(L) | Extends the list by appending all elements from the specified list, equivalent to a[len(a):] = L. |
| list.insert(i, x) | Inserts an element at the specified position. The first parameter is the index of the element before which to insert. For example, a.insert(0, x) inserts before the entire list, while a.insert(len(a), x) is equivalent to a.append(x). |
| list.remove(x) | Removes the first element from the list whose value is x. If there is no such element, an error is returned. |
| list.pop([i]) | Removes the element at the specified position from the list and returns it. If no index is specified, a.pop() returns the last element. The element is immediately removed from the list. (The square brackets around i in the method indicate that this parameter is optional, not that you need to type square brackets. You will often encounter such notation in the Python Library Reference.) |
| list.clear() | Removes all items from the list, equivalent to del a[:]. |
| list.index(x) | Returns the index of the first element in the list whose value is x. If there is no matching element, an error is returned. |
| list.count(x) | Returns the number of times x appears in the list. |
| list.sort() | Sorts the elements of the list. |
| list.reverse() | Reverses the elements of the list. |
| list.copy() | Returns a shallow copy of the list, equivalent to a[:]. |
The following example demonstrates most list methods:
Example
Section titled “Example”Note: Methods like insert, remove, or sort that modify the list have no return value.
Using Lists as Stacks
Section titled “Using Lists as Stacks”In Python, you can use lists to implement stack functionality. A stack is a Last-In-First-Out (LIFO) data structure, meaning the last element added is the first one to be removed. Lists provide methods that make them very suitable for stack operations, especially the append() and pop() methods.
Use the append() method to add an element to the top of the stack, and use the pop() method without specifying an index to remove an element from the top of the stack.
Stack Operations
Section titled “Stack Operations”- Push: Adds an element to the top of the stack.
- Pop: Removes and returns the top element of the stack.
- Peek/Top: Returns the top element without removing it.
- IsEmpty: Checks whether the stack is empty.
- Size: Gets the number of elements in the stack.
The following is a detailed explanation of how to implement these operations using lists in Python:
1. Create an empty stack
Section titled “1. Create an empty stack”Example
Section titled “Example”2. Push operation
Section titled “2. Push operation”Use the append() method to add an element to the top of the stack:
Example
Section titled “Example”3. Pop operation
Section titled “3. Pop operation”Use the pop() method to remove and return the top element:
Example
Section titled “Example”4. Peek/Top
Section titled “4. Peek/Top”Directly access the last element of the list (without removing it):
Example
Section titled “Example”5. IsEmpty
Section titled “5. IsEmpty”Check whether the list is empty:
Example
Section titled “Example”6. Size
Section titled “6. Size”Use the len() function to get the number of elements in the stack:
Example
Section titled “Example”Example
Section titled “Example”The following is a complete example showing how to use the above operations to implement a simple stack:
Example
Section titled “Example”In the above code, we defined a Stack class that encapsulates a list as the underlying data structure and implements the basic stack operations.
The output is as follows:
Using Lists as Queues
Section titled “Using Lists as Queues”In Python, lists can be used as queues. However, due to the characteristics of lists, using lists directly to implement queues is not the optimal choice.
A queue is a First-In-First-Out (FIFO) data structure, meaning the earliest added element is the first to be removed.
When using lists, if you frequently insert or delete elements at the beginning of the list, performance will be affected because these operations have a time complexity of O(n). To solve this problem, Python provides collections.deque, which is a double-ended queue that can efficiently add and remove elements at both ends.
Using collections.deque to Implement a Queue
Section titled “Using collections.deque to Implement a Queue”collections.deque is part of the Python standard library and is very suitable for implementing queues.
The following is an example of implementing a queue using deque:
Example
Section titled “Example”Using a List to Implement a Queue
Section titled “Using a List to Implement a Queue”Although deque is more efficient, if you insist on using a list to implement a queue, you can also do so. Here is how to implement a queue using a list:
1. Create a queue
Example
Section titled “Example”2. Add elements to the end of the queue
Use the append() method to add elements to the end of the queue:
Example
Section titled “Example”3. Remove an element from the front of the queue
Use the pop(0) method to remove an element from the front of the queue:
Example
Section titled “Example”4. Peek at the front element (without removing)
Directly access the first element of the list:
Example
Section titled “Example”5. Check if the queue is empty
Check whether the list is empty:
Example
Section titled “Example”6. Get the queue size
Use the len() function to get the queue size:
Example
Section titled “Example”Example (Using a List to Implement a Queue)
Section titled “Example (Using a List to Implement a Queue)”Example
Section titled “Example”Although you can use a list to implement a queue, using collections.deque is more efficient and concise. It provides O(1) time complexity for add and remove operations, making it very suitable for queue data structures.
List Comprehensions
Section titled “List Comprehensions”List comprehensions provide a concise way to create lists from sequences. Typically, applications apply some operation to each element of a sequence, using the obtained result as the element for generating a new list, or create subsequences based on certain filtering conditions.
Each list comprehension is followed by an expression after for, and then zero or more for or if clauses. The result is a list generated from the expression in the context of the for and if clauses that follow. If you want the expression to derive a tuple, you must use parentheses.
Here we multiply each value in the list by three to obtain a new list:
Now let’s play some tricks:
Here we call a method on each element of the sequence one by one:
Example
Section titled “Example”We can use an if clause as a filter:
Here are some demonstrations of loops and other techniques:
List comprehensions can use complex expressions or nested functions:
Nested List Comprehensions
Section titled “Nested List Comprehensions”Python lists can also be nested.
The following example shows a 3X4 matrix list:
The following example converts a 3X4 matrix list into a 4X3 list:
The above example can also be implemented using the following method:
Another implementation method:
The del Statement
Section titled “The del Statement”Use the del statement to remove an element from a list by index rather than by value. This is different from using pop() which returns a value. You can use the del statement to remove a slice from a list or clear the entire list (the method we previously introduced was to assign an empty list to the slice). For example:
You can also use del to delete an entity variable:
Tuples and Sequences
Section titled “Tuples and Sequences”A tuple consists of several values separated by commas, for example:
As you can see, tuples are always output with parentheses to correctly express nested structures. When inputting, parentheses may or may not be present, though parentheses are usually required (if the tuple is part of a larger expression).
A set is an unordered collection of unique elements. Basic functions include membership testing and eliminating duplicate elements.
You can create a set using curly braces ({}). Note: To create an empty set, you must use set() instead of {}; the latter creates an empty dictionary, which we will introduce in the next section.
Here is a simple demonstration:
Sets also support comprehensions:
Dictionaries
Section titled “Dictionaries”Another very useful Python built-in data type is the dictionary.
Unlike sequences, which are indexed by consecutive integers, dictionaries are indexed by keys, which can be any immutable type, typically strings or numbers.
The best way to understand a dictionary is to think of it as an unordered key=>value pair collection. Within the same dictionary, keys must be unique.
A pair of curly braces creates an empty dictionary: {}.
Here is a simple example of dictionary usage:
The dict() constructor builds dictionaries directly from lists of key-value pair tuples. If there is a fixed pattern, list comprehensions can specify specific key-value pairs:
In addition, dictionary comprehensions can be used to create dictionaries with arbitrary key and value expressions:
If the keys are simple strings, it is sometimes more convenient to specify key-value pairs using keyword arguments:
Iteration Techniques
Section titled “Iteration Techniques”When iterating through a dictionary, the key and corresponding value can be retrieved simultaneously using the items() method:
When iterating through a sequence, the index position and corresponding value can be obtained simultaneously using the enumerate() function:
To iterate through two or more sequences simultaneously, use the zip() combination:
To iterate through a sequence in reverse, first specify the sequence, then call the reversed() function:
To iterate through a sequence in sorted order, use the sorted() function to return a sorted sequence without modifying the original: