What is typically regarded as more Pythonic/better/faster to use, the reverse method or the reversed built-in function?
Both in action:
_list = list(xrange(4)) print _list rlist = list(reversed(_list)) print rlist _list.reverse() print _list
The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.
Using the reversed() method and reverse() method, we can reverse the contents of the list object in place i.e., we don't need to create a new list instead we just copy the existing elements to the original list in reverse order. This method directly modifies the original list.
In order to reverse a list without using the built-in reverse() function, we use the Slicing Operator. The slicing operator is another method used for reversing the data elements. Let us understand this by looking at an example.
In this process, reversed version of given string is created and is assigned to our original string. Time Complexity of this approach is O ( N ) O(N) O(N) where N is the length of the string to be reversed.
foo.reverse()
actually reverses the elements in the container. reversed()
doesn't actually reverse anything, it merely returns an object that can be used to iterate over the container's elements in reverse order. If that's what you need, it's often faster than actually reversing the elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With