_

Always be tactful

Insights (종료)/For EN

[Python] Three Methods to Reverse a List

funczun 2024. 12. 6. 12:06
Three Methods to Reverse a List

 

[::-1]

 This method reverses the list by slicing it in reverse order. It creates a new list, so if the list is very large, it can lead to unnecessary memory usage.

 

reverse()

 This method directly reverses the original list, which means it uses less memory. However, since it modifies the original list, it should not be used if you want to keep the original list intact.

 

reversed()

 This method returns an iterator, so the original list remains unchanged while using less memory. However, it cannot be used directly as a list; you need to convert it to a list using list().


Conclusion
  • If it’s acceptable to modify the original list → reverse()
  • If you need to preserve the original list and its size is small → [::-1]
  • If you need to preserve the original list and its size is very large → reversed()

 ※ While the criteria are based on the size of the list, the underlying consideration is memory usage. Larger lists consume more memory, which is why the explanation uses size as a guideline. A "small" list is defined as having around 100 elements, while a "large" list refers to those exceeding 10,000 elements.

728x90