[Tutor] searching for a string in a dictionary

Alan Gauld alan.gauld at freenet.co.uk
Wed Aug 9 13:11:44 CEST 2006

> doesTypeExist=filter(lambda x: typeofstring in x.type, all_types)
> if 'teststring' in [s.type for s in all_types]
> this works which is better in terms of speed???

These do two different things.
The first returns a list of all_types entries that match
The second returns true or false if *any* string matches.

The first can be rewritten without lambda using a list comprehension:

[ item for item in all_types if teststring in item['type'] ]

Calling functions in python is usually fairly slow so using 
with its function call per item is probably slower than either of the
list comprehension methods. If in doubt measure it...

Alan G.

More information about the Tutor mailing list