I use list comprehensions probably about as much as any intermediate or advanced Python programmer. I try not to use over do it.
I’m curious if this would seem obscure or merely terse:
some_count = len([x for x in some_list if x in some_dict])
… in lieu of:
some_count = 0
for x in some_list:
if x in some_dict:
some_count += 1
In the actual case I’m looking at I could even use:
some_count = len(set(some_list) & set(some_dict))
(Given that the items in some_list are guaranteed to be distinct).
In particular I have a function with returns a (possibly empty) list of strings (from an external, proprietary data store). It should be the case that only one of these is a valid key into a dictionary in my code. If it’s zero I should post a warning, if it’s one I should just the the value from my code, and if it’s more than one I should emit an error.
I’m just soliciting stylistic opinions here.
The condition
x in some_dict(x)is very obscure; looks like you need to lose the(x).You don’t need to build a list; try this:
some_count = sum(1 for x in some_list if x in whatever)Your set approach seems to be the most understandable. It’s not likely to be the fastest, however.