Home > Python, Tech > Reversing Python list/string objects

Reversing Python list/string objects

I was interested in the relative performance of reversing a python list using the idom list[::-1] rather than the reverse method of the list class. Additionally I wanted to see if this idom was efficient for reversing strings compared to converting to a list, reversing that list, and joining the elements again using ''.join(reversed_list). Here are the results:

Reverse list, slicing: (0.58000000000000007, 0.64144396781921387)
Reverse list, method: (0.20000000000000018, 0.19551301002502441)
Reverse string, slicing: (0.45000000000000001, 0.49545693397521973)
Reverse string, list: (3.71, 3.7981550693511963)

I’m using a quick Timer class that I implemented to report the running time for a chunk of code using both of time.clock() (the first item) and time.time() (the second item). Here is the code used to produce these results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import time
from collections import namedtuple
from copy import deepcopy
 
class Timer(object):
   Times=namedtuple('times','clock time')
 
   def __init__(self):
      self.running=False
 
   def _set_times(self,field_name):
      times=Timer.Times(time.clock(),time.time())
      setattr(self,field_name,times)
 
   def start(self):
      if self.running: raise ValueError('Timer is already running!')
      self.running=True
      self._set_times('tstart')
   def stop(self):
      if not self.running: raise ValueError('Timer is not running!')
      self.running=False
      self._set_times('tstop')
 
   def time(self):
      return (self.tstop.clock-self.tstart.clock,self.tstop.time-self.tstart.time)
 
timer=Timer()
test_string='Time flies like an arrow.  Fruit flies like a banana.'
test_list=list(test_string)
iterations=1000000
 
timer.start()
for i in xrange(iterations):
   new_string=test_string[::-1]
timer.stop()
print 'Reverse string, slicing:',timer.time()
 
timer.start()
for i in xrange(iterations):
   l=list(test_string)
   l.reverse()
   new_string=''.join(l)
timer.stop()
print 'Reverse string, list:',timer.time()
 
timer.start()
for i in xrange(iterations):
   test_list=test_list[::-1]
timer.stop()
print 'Reverse list, slicing:',timer.time()
 
timer.start()
for i in xrange(iterations):
   test_list.reverse()
timer.stop()
print 'Reverse list, method:',timer.time()

Feel free to use any of this code yourself, consider it under a BSD license. Particularly the Timer class has been useful for me in multiple cases.

Based on the timing results, I’d say it looks best to use the slicing idiom on strings and the reverse method on lists.

  1. No comments yet.
  1. No trackbacks yet.