Reverse order of list

List elements in reverse order

list.reverse() The
list.reverse() method will directly arrange the elements in the original list in reverse order. There is no need to create a new copy to store the result, and there is no need to re-apply for space to save the final result, but it is modified The original data.

list[::-1]
Python lists have a feature called slicing. mylist[:] will return a copy of mylist. When start, end, and step are negative, it means traversing from the opposite direction, so mylist[::-1] Can achieve the purpose of reverse order. Compared with the first method, this method will create another copy to save all the elements of the list, so more memory space is required.

reversed() The
reversed method will store the result of the reverse order of the list in the iterator. This method will not change the original list, nor create a complete copy of the original list. It will only increase the space occupied by the iterator object. It is also more efficient. In other words, the return value is an iterator, you can understand it as a pointer to the original list.

Guess you like

Origin blog.csdn.net/plan_jok/article/details/110674736