Some intriguing discussions on performance happened here, so let me provide a benchmark:
http://ideone.com/ldId8
noslice_map : 0.0814900398254
slice_map : 0.084676027298
noslice_comprehension : 0.0927240848541
slice_comprehension : 0.124806165695
iter_manual : 0.133514881134
iter_enumerate : 0.142778873444
iter_range : 0.160353899002
So:
map(str.strip, my_list)
is the fastest way, it's just a little bit faster than comperhensions.
- Use
map
or itertools.imap
if there's a single function that you want to apply (like str.split)
- Use comprehensions if there's a more complicated expression
- Manual iteration is the slowest way; a reasonable explanation is that it requires the interpreter to do more work and the efficient C runtime does less
- Go ahead and assign the result like
my_list[:] = map...
, the slice notation introduces only a small overhead and is likely to spare you some bugs if there are multiple references to that list.
- Know the difference between mutating a list and re-creating it.