Saturday, May 18, 2013

python's shortcuts

Let's try to optimize some simple python code like this:
a = ['eggs', 'bacon']

no_spam = True
for x in a:
    if x == 'spam':
        no_spam = False
if no_spam:
    print('there is no spam in it')
This might seem pretty obvious but an often forgotten fact is that a python's for loop may have an optional else clause.

So to make it slightly shorter and avoid using an additional variable:
a = ['eggs', 'bacon']

for x in a:
    if x == 'spam':
        break
else:
    print('there is no spam in it')
If you want to make if even shorter you can use the built-in functions any and map instead of the for loop:
a = ['eggs', 'bacon']

if not any(map(lambda x: True if x == 'spam' else False, a)):
    print('there is no spam in it')

2 comments:

Unknown said...

if not "spam" in a:

robotnaoborot said...

if not any(map(lambda x: x == 'spam', a)):
print('there is no spam in it')