Use the in operator
I often see code like this:
if value == 'cheese' or value == 'bacon':
print "Mmm!"
A much nicer alternative is:
if value in ('cheese', 'bacon'):
print "Mmm!"
Specially since you can now refactor this to:
YUMMIE_THINGS = ('cheese', 'bacon')
if value in YUMMIE_THINGS:
print "Mmm!"
And use that same list of yummie things in other places in the code without having to worry that they get out of sync.
This works fine with types other than strings too of course.
Written by Stefan Arentz
Related protips
3 Responses
I just fixed some older code that I had written that did this. Perhaps I had added the second check later, but at any rate I refactored it yesterday. I used a list, however, as opposed to a tuple:
if value in ['cheese', 'bacon']:
I would say for values like this the performance is essentially the same, but is there a reason to favor one over the other?
I guess this answers my question (thanks @corbinbs):
http://stackoverflow.com/questions/3340539/why-tuple-is-faster-than-list/3340881#3340881
I'll make a final tweak to use a tuple. :)
Just a small precision, it does not work with list of list
and with NaN
;)