So for the longest time I was big on writing my if/else statements in a very old school way, which for the most part was fine. However the other day I was working with someone at work and they showed me perhaps the most glorious way to turn what at the minimum is a 4 line block of code into a single line.

Here is how I used to do it prior to this enlightening pair-programming moment.

if some_value == expected_value:
    result = True
    result = False

It may not seem like a huge savings but when your files easily hit 200 lines or more being able to condense a little bit adds up over time, so here is how to bust this down to a single line of code, and its fantastic

result = True if found_value == expected_value else False

It seems so plain but I guess being stuck in my old ways of writing things it never occurred to me that it could be condensed so much. That being said I don’t know if I would use this method all the time as it could be confusing in example code intended for relatively new programmers but for production things at work this is the bees knees!

Leave a Reply

Your email address will not be published.

Close Bitnami banner