3 ways Python list in reverse order

1. The list element in reverse order

  • list.reverse()

    list.reverse () method directly in the original list of elements which will be in reverse order, no need to create a new copy to store the result, do not need to re-apply for space to hold the final result, but modifying the original data.

  • list[::-1] 

    Python's list has a feature called slices, mylist [:] returns a copy of mylist when the start, end and step is negative, represents the traversal from the opposite direction, so mylist [:: - 1] will be able to achieve the purpose of the reverse order. Compared to the first approach, this approach will create another copy to save the list of all the elements, so they need more memory space.

  • reversed() 

    reversed method will store the result of the list in reverse iterator inside, this way will not change the original list, it will not create a complete copy of the original list, only the extra space occupied by the iterator object, relatively speaking, too more efficient. That return value is an iterator, you can be understood as a pointer to the original list.

2. References

u=2550706319,297457175&fm=173&app=25&f=JPEG?w=640&h=365&s=12B5716C1BE49B6C1AD6B4030200A0CBuploading.4e448015.gifDump failed to re-upload canceled

Published 38 original articles · 98 won praise · views 360 000 +

Guess you like

Origin blog.csdn.net/xijuezhu8128/article/details/88555003