[Python Fennel Bean Series] How to reverse a list

When programming in Python, it is sometimes interesting to use different methods to accomplish the same goal.
This reminds me of Lu Xun's Kong Yiji. Kong Yiji did a lot of research on the four ways of writing the word fennel for fennel beans. I
dare not compare myself to Kong Yiji, so here I collect some Python fennel beans for the enjoyment of all coders.

In Python programming, we often encounter reverse-order lists. Suppose there is a list:
[1, 2, 3, 4, 5]. We need to get the reverse-order list of this list, that is, [5, 4, 3, 2, 1 ].
Next we first prepare the source list:

>>> source_list = [1, 2, 3, 4, 5]

Fennel Bean One: Using a For Loop

To reverse a list, the honest method is to use a loop, starting from the end of the source list, taking
an element in reverse order and adding it to the target list, and then printing the target list.

>>> target_list = list()
>>> for index in range(len(source_list)):
>>>     target_index =  - index -1
>>>     target_list.append(source_list[target_index])
>>> print(target_list)
[5, 4, 3, 2, 1]

Of course, if you use list comprehension, the above content can be written as one line of code:

>>> print([source_list[(- index -1)] for index in range(len(source_list))])
[5, 4, 3, 2, 1]

Fennel Bean 2: Using the reverse method of a list

Of course, the above method is a bit complicated, and we need a simpler method. According to the official documentation, the list
itself has a reverse method, whose function is to reverse the order of the list. Examples are as follows:

>>> source_list.reverse()
>>> print(source_list)
[5, 4, 3, 2, 1]

This method is simple and practical, as long as you can memorize the words. Note, however, that this method will change
the contents of the list itself. If we don't want to change its contents, we need to create a copy of the list first. Examples are as follows:

>>> source_list = [1, 2, 3, 4, 5]
>>> target_list = source_list[:]
>>> target_list.reverse()
>>> print(source_list)
>>> print(target_list)
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

Fennel Bean Three: Using the reversed class

Having trouble creating a copy? Then use the reserved class, which is built-in in Pyton. Its function returns
an iterator in reverse order of a given sequence. It’s a bit hard to pronounce, look at the example:

>>> print(list(reversed(source_list)))
[5, 4, 3, 2, 1]

Note that because reversed returns an iterator, we use the list class here to convert the iterator
into a list. If you just need to know how to reverse a list, then knowing reverse and
reversed is enough. They are all built-in in Python, they are efficient and convenient, and you won’t suffer any loss if you use them.

This article is not finished yet. Friends who have spare time to learn but have nothing to do, please go to my private area: https://dy2018.gitlab.io/ to view more content.

Guess you like

Origin blog.csdn.net/mouse2018/article/details/121181563