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.
'Insights (종료) > For EN' 카테고리의 다른 글
[CS] 1.1 + 0.1 != 1.2, Why? (1) | 2024.12.13 |
---|---|
[GitHub] Deleting the Most Recent Commit (0) | 2024.11.29 |
[Python] BOJ 11718: No input values, No EOFError? (0) | 2024.11.22 |
[Python] BOJ 2675: Escape Character with a Debugger (1) | 2024.11.15 |
[Python] BOJ 10809: Does the find() return only the index? (3) | 2024.11.08 |