Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's "better" the reverse method or the reversed built-in function?

Tags:

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 
like image 721
rectangletangle Avatar asked Jul 24 '11 22:07

rectangletangle


People also ask

What's the point of reverse ()?

The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.

What is the use of reverse () method in the 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.

How do I reverse a list without using built-in function?

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.

What is the time complexity of reversing a string in Python?

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.


1 Answers

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.

like image 61
kindall Avatar answered Sep 20 '22 06:09

kindall