How to efficiently proceed addition and subtraction in python list?
Steve Holden
steve at holdenweb.com
Tue Sep 19 08:27:22 EDT 2006
Ant wrote:
> Tim Chase wrote:
>
>>>I have a list AAA = [1, 2, 3] and would like to subtract one from list
>>>AAA
>>>so AAA' = [0, 1, 2]
>>>
>>>What should I do?
>>
>>
>>Sounds like a list comprehension to me:
>
>
> Also the built in function 'map' would work:
>
>
>>>>a = [1,2,3]
>>>>b = map(lambda x: x-1, a)
>>>>b
>
> [0, 1, 2]
>
> List comprehensions are more pythonic, but map would probably be faster
> if performance was a (real) issue.
>
And statements like that are probably going to annoy me ;-)
>>> t = timeit.Timer("b = map(lambda x: x-1, a)", setup="a=[1,2,3]")
>>> t.timeit()
2.4686168214116599
>>> t = timeit.Timer("b = [x-1 for x in a]", setup="a=[1,2,3]")
>>> t.timeit()
0.9930245324475635
>>>
Any timing prediction involving the word "probably" isn't worth the
paper it's written on (or even less if it's posted in a newsgroup ;-).
If it's "probably" faster, and if performance is *really* important, you
need to benchmark both options to remove the "probably". As the above
test makes clear, your assertions are certainly untrue for 2.4.2 on Windows.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list
mailing list