1 Introduction
Currently, Python is one of the most widely used and popular programming languages in the world. The rich functionality of Python makes it very popular because we can create anything with it. In this blog, I will share with you a few interesting tidbits about Python lists.
Without further ado, let's get started!
2. List as a stack
In the list, we can use functions pop
to realize the function of the stack. We know that the characteristics of the stack are 先进后出
, let's look at an example as follows:
3. Lists as Queues
In the list, we can realize the function of the queue by pop
passing parameters to the function 0
. We know the characteristics of the queue 先进先出
. Let's look at an example as follows:
4. Lists are used as deques
In the list, we can use the function pop
and insert
to realize the function of the double-ended queue. The characteristic of the double-ended queue is that the tail of a queue is also the head of the queue; both ends can perform queue and join operations. Examples are as follows:
5. Various sorts of lists
The basic sorting function of the list by using the function sort
is as follows:
We can also control the descending operation of the list through parameters, as follows:
Of course, we can also perform corresponding sorting operations on lists containing complex elements, as follows:
6. List slice operation
Typically, we use array[x:y]
slice operations, which usually give us values from array[x]
to . array[y-1]
However, few people know that we can use array[x:y:z]
to provide us with values from array[x]
to array[y-1]
with an interval of z
.
Examples are as follows:
7. Multiple ways to iterate over an array
There are three ways to iterate over an array:
-
Indexing from front to back: where
a[0]
is the first element in the array,a[1]
is the second element in the array, and so on. -
Indexing from back to front: Here,
a[-1]
is the last element of the array,a[-2]
the second last element of the array, and so on. Mathematically,[-i]
it is equivalent[n-i]
. -
Use
~
for indexing: In this case,a[~1]
means the second last element,a[~2]
means the third last element, and so on. Mathematically,[~i]
it is equivalent to[n-i-1]
. Personally, when it comes to writing code, I find it much better[~i]
than writing[n-1-i]
.
A sample is as follows:
8. Summary
This article focuses on some uncommon operations in Python lists. Many operations are often difficult to implement, perhaps because we are not familiar with some special skills. The corresponding skills in this article give corresponding code examples. I hope you can apply what you have learned.
Have you lost your studies?