Reverse a List with Python Slicing

👀 How do you reverse a list using just ONE single line ❓ ❓ ❓ There are algorithms you can use to completely reverse a list. But if you need something short and simple: 🐍 Python has the Slicing technique❗ ❗ ❗ It is a powerful technique for extracting portions of sequences such as lists, strings, or tuples, using a concise and efficient syntax. nameList[ start : stop : step ] start => Index where the slice begins (included) stop => Index where the slice ends (not included). step => Increment between elements (optional, default is 1). If you wish to retrieve the entire list: 👉 nameList[ : ] If you want to REVERSE the ENTIRE list, just leave the start and stop empty and make the step negative. 👉 nameList[ : : -1] #Python #AI #Programming

  • text

the problem is this code are not same nither from the point of memory nor from behavior. The first mutates the original item, so if there is somewhere outside of the function a ref to the ITEM, it would be changed. The slice CREATES new list. And if it not a few items but a big array of shitty heavy object, you just doubled memory it ate

It depends on your goal. For instance, the second method is better if you need a new list, but items.reverse() is faster if you don't mind mutating the original list.

See more comments

To view or add a comment, sign in

Explore content categories