On Thu, Dec 6, 2012 at 10:47 PM, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > Not so. Which one is faster will depend on how often you expect to fail. > If the keys are nearly always present, then: > > try: > do_stuff(mydict[k]) > except KeyError: > pass > > will be faster. Setting up a try block is very fast, about as fast as > "pass", and faster than "if k in mydict". > > But if the key is often missing, then catching the exception will be > slow, and the "if k in mydict" version may be faster. It depends on how > often the key is missing. >
Setting up the try/except is a constant time cost, while the duplicated search for k inside the dictionary might depend on various other factors. In the specific case of a Python dictionary, the membership check is fairly cheap (assuming you're not the subject of a hash collision attack - Py3.3 makes that a safe assumption), but if you were about to execute a program and wanted to first find out if it existed, that extra check could be ridiculously expensive, eg if the path takes you on a network drive - or, worse, on multiple network drives, which I have had occasion to do! ChrisA -- http://mail.python.org/mailman/listinfo/python-list