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.
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.
There seems to be a great difference. I really thought it's the other way round. Why is rearranging the values in a list faster than creating a new one from an iterator ?
from decorators import bench
_list = range(10 ** 6)
@ bench
def foo():
list(reversed(_list))
@ bench
def bar():
_list.reverse()
foo()
bar()
print foo.time
print bar.time
0.167278051376
0.0122621059418
I always thought that slice operation for reversing of the list or something else is fastest one. But after watching "Transforming Code into Beautiful, Idiomatic Python" on youtube I have decided to compare slice and reversed method to each other. Obviously reversed is faster than slicing when we assign the result to new variable. But when we want just to reverse without having new variable results are roughly the same or even better for slicing . Here is the graph and tested code
graphs!
import timeit example = ''' d = [1,2,3,4,5,6,7,8,9,0] d = reversed(d) ''' example2 = ''' d = [1,2,3,4,5,6,7,8,9,0] d = d[::-1] ''' print(timeit.timeit(example, number=100000000)) print(timeit.timeit(example2, number=100000000)) import timeit example = ''' d = [1,2,3,4,5,6,7,8,9,0] new_var = reversed(d) ''' example2 = ''' d = [1,2,3,4,5,6,7,8,9,0] new_var = d[::-1] ''' print(timeit.timeit(example, number=100000000)) print(timeit.timeit(example2, number=100000000))
Should programmer choose carefully between slicing and reversed?