The first, using the reversed function, is that reversed returns a reversed iterator, which we need to convert to list
listNode = [1,2,3,4,5] newList = list(reversed(listNode)) print(newList) #Results [5,4,3,2,1]
The second, using the sorted function, sorted is a sorting function, it is a list of a list of sorted to generate a new list list, while sort is in the original list directly on the sorting.
listNode = [1,2,3,4,5] newList = sorted(listNode,reverse = True) print(newList) #Results [5,4,3,2,1]
where reverse is the sorting rule, True means sort in descending order, False means sort in ascending order, and False is the default value.
The third, using slicing techniques
listNode = [1,2,3,4,5] li = listNode[::-1] print(li) #Results [5,4,3,2,1]
The format of the slice [0:3:1], where the subscript 0 refers to the first element of the sequence (left border), the subscript 3 can refer to the number of slices (right border), the parameter 1 means that the step of the slice is 1, and if it is -1 it means that the slicing is done from the right side and the step is 1. The slices don't include the right border subscript.
[ : ] means get all the elements of the sequence, omitting the step will default the step to 1.
Fourth, use loops, recursion
listNode = [1,2,3,4,5] new=[] head=listNode while head!=None: () head= () print(new)
def getLists(self,listNode): if listNode is None: return [] l = () return l + [] lists = [1,2,3,4,5] getLists(lists)
Where + joins multiple smaller lists to form a completely new larger list, which is equivalent to creating a new list using multiple values or lists, e.g., there exists a list l = [1,2], and when we run l = l + [3] the l result is [1,2,3].
Also append adds a value to the list, but append is equivalent to modifying the list, e.g. when we execute ([3]) the result of the list will be [1,2,[3]].
To this article on the Python list of four ways to reverse the display of the article is introduced to this, more related to the Python list of inverted content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!