Python Tutorial List Tool

Mondo Technology Updated on 2024-01-19

Hi guys!Today we're going to dive into some of the powerful list tools in Python to make your programming journey even more handy.

Python tutorial programming skills

1.Array module

First, let's talk about array modules. This module provides us with a more compact and efficient list, which is particularly suitable for storing similar data. Looking at this example, we can store double-byte unsigned binary arrays of numbers instead of the usual python int object list:

from array import array

a = array('h', [4000, 10, 700, 22222])

print(sum(a))

Output: 26932

print(a[1:3])

Output: array('h', [10, 700])

Output

array('h', [10, 700])

Explain

When we usefrom array import arrayAfter importing the array module, we can create an array object whose first argument to the constructor is the type, which represents the type of the elements in the array. Here it is'h'Indicates that each element is a double-byte unsigned short (unsigned short), and the type can be selected according to your needs, for example'i'Represents a signed integer.

Next, we create an array a and initialize some values [4000, 10, 700, 22222]. This array will store these values as double-byte unsigned integers.

a = array('h', [4000, 10, 700, 22222])

Then, we use sum(a) to sum the array. Here, all the elements in the array (4000 + 10 + 700 + 22222) will be summed up for the output of 26932.

print(sum(a))

Output: 26932

Finally, we use the slicing operation a[1:3] to get the elements in the array with indexes from 1 to 2 (excluding index 3) and output them. The output here is a new array containing the elements of the original array with indexes 1 to 2 [10, 700].

print(a[1:3])

Output: array('h', [10, 700])

Overall, this section demonstrates how to create and manipulate a double-byte containing array module.

An array of unsigned integers, which demonstrates the flexibility and functionality of arrays through sum summing and slicing operations. This is useful when working with large amounts of numerical data, especially when more compact storage and high performance are required.

2.Double-ended queues (deque).

Next, let's take a look at the double-ended queue, which is a list-like object, but appends and pops faster on the left. It's great for implementing queues and breadth-first searches

from collections import deque

def gen_moves(node):

Generates all possible substrings for a given string node.

moves =

for i in range(len(node)):

for j in range(i + 1, len(node) +1):

moves.append(node[i:j])

return moves

def is_goal(node):

In this example, the target state is a string with a string length of 5.

return len(node) == 5

Create a double-ended queue to represent a list of pending tasks.

d = deque(["task1", "task2", "task3"])

will be a new task"task4"Added to the tail of the queue.

d.append("task4")

This section displays the process of processing tasks in a double-ended queue.

print("original task list:", d)

print("handling", d.popleft())

print("updated task list:", d)

Define the start node.

starting_node = "initial_node"

Create a double-ended queue that contains the start node.

unsearched = deque([starting_node])

Define a breadth-first search function.

def breadth_first_search(unsearched):

A node pops up from the left side of the queue.

node = unsearched.popleft()

Move the current node.

for m in gen_moves(node):

If the target state is reached, the result is returned.

if is_goal(m):

return m

Add a new node to the queue.

unsearched.append(m)

Demonstrate the process of breadth-first search.

print("unsearched nodes:", unsearched)

In the process of breadth-first search, determine whether the target state has been reached.

result = breadth_first_search(unsearched)

print("result of breadth-first search:", result)

Output

original task list: deque(['task1', 'task2', 'task3', 'task4'])

handling task1

updated task list: deque(['task2', 'task3', 'task4'])

unsearched nodes: deque(['initial_node'])

result of breadth-first search: initi

Explain

The is goal function checks whether the length of the string is equal to 5, indicating that the target state has been reached. In a real problem, you need to define the is goal function based on your search goal to make sure it meets the requirements of the problem.

3.bisect module

In addition to the basic list operations, we also have the bisect module, which provides the ability to perform a binary lookup in a sorted list:

import bisect

scores = [(100, 'perl'), 200, 'tcl'), 400, 'lua'), 500, 'python')]

bisect.insort(scores, (300, 'ruby'))

print(scores)

Output: [100,.]'perl'), 200, 'tcl'), 300, 'ruby'), 400, 'lua'), 500, 'python')]

Output

[(100, 'perl'), 200, 'tcl'), 300, 'ruby'), 400, 'lua'), 500, 'python')]

Explain

bisect.insort(scores, (300, 'ruby')): This line will add tuples (300,'ruby') into the sorted scores list. The insort function ensures that the list remains sorted after insertion.

print(scores): This line prints the list of inserted scores.

Note that the new tuple (300,'ruby') is correctly inserted into the scores, and the list remains sorted in ascending order. This technique is useful for dynamic datasets that need to be kept sorted.

4.HEAPQ module

Finally, let's look at the HEAPQ module, which provides a general heap-based list. This is useful for repeating access to minimal elements, but you don't want to run a full list sort:

from heapq import heapify, heappop, heappush

data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]

heapify(data)

heappush(data, -5)

print([heappop(data) for i in range(3)])

Output: [5, 0, 1].

Output

Explain

heapify(data): This line uses the heapify function to convert the list data into a heap. A heap is a special tree-like data structure in which the value of each node is less than or equal to the value of its child nodes.

heappush(data, -5): This line uses the heappush function to push the new element -5 into the heap. This will maintain the nature of the heap, i.e. the value of any node in the heap is less than or equal to the value of its children.

heappop(data) for i in range(3)]: This line uses list inference, and executes heappop(data) in a loop three times, each time ejecting the smallest element in the heap. Due to the nature of the heap, each ejected element is the minimum in the heap.

print(result): Finally, print the result, which are the first three smallest elements. The output is [-5, 0, 1].

This approach to using heaps is ideal for situations where the smallest elements in a dynamic collection need to be maintained, since the time complexity of inserting and ejecting the smallest elements in the heap is o(log n).

That's what we're sharing today about the Python list tool!Hopefully, these tools will help you in your coding journey. If you have any questions or want to learn more about a tool, please leave a comment in the comment section and I will do my best to answer them. Remember to like, share, subscribe, and be with you on the road to programming!Thanks for watching, and we'll see you next time!

Related Pages