Eliminate If from Your Code

Introduction

We often write code with too many if statements. If statements are fine, but in many cases, we can eliminate them, making the code simpler and faster.

Example 1: The "or" Trick

In this example, we create a linked list data structure:

class List(object):
    def __init__(self, iterable=None):
        self.head = None
        self.tail = None
        self.length = 0
        if iterable:
            for item in iterable:
                self.append(item)

In this example, the linked list's __init__ method takes in an optional iterable object (an object that we can iterate through). If the iterable is not None, we then iterate through it and append them one by one. At the first glance, the if statement does have its place: it prevents the for loop from iterating over a None object, which causes runtime error.

The key to remove the if statement lies in the fact that we cannot iterate through the None object, but an empty list:

class List(object):
    def __init__(self, iterable=None):
        self.head = None
        self.tail = None
        self.length = 0
        for item in iterable or []:
            self.append(item)

The expression iterable or [] will return the iterable if it is "true", or an empty list if not. When iterable is None, we will iterate through an empty list, which means the body of the for loop will execute zero times.

Example 2: Toggle Values

Consider the following pattern:

if flag:
    flag = False
else:
    flag = True

This block of code toggles the value of flag between True and False. A simpler and more efficient way is:

flag = not flag

Example 3: Boolean Equality Test

Believe it or not, I see the following a few times in my career:

if expected == True and actual == True:
    return True
elif expected == False and actual == False:
    return True
else return False

Or:

if (expected == True and actual == True) or \
   (expected == False and actual == False):
    return True
else return False

The two blocks above say:

If the values of actual and expected are both True or are both False then we return True, otherwise we return False.

In other word, these blocks test to see if actual is the same as expected:

return actual == expected

Example 4: Nested If

I also frequently see code like this:

if wrap_around:
    if x == MAX_WIDTH:
        x = 0
        y += 1

Depend on the situation, we might not be able to eliminate the if statements altogether, but we can reduce the nesting:

if wrap_around and x == MAX_WIDTH:
    x = 0
    y += 1

Example 5: Cycle of Values

In the following example, the coder wanted value of column to cycle between 0 and 7:

column = 0
for cell in data:
    # do something
    column += 1
    if column == 8:
        column = 0

The quick and easy way to improve this code is to employ the modulus operator:

column = 0
for cell in data:
    # do something
    column = (column + 1) % 8

Another fix is to use the cycle function:

from itertools import izip, cycle

for column, cell in izip(cycle(range(8)), data):
    # Do something

In this case, range(8) returns [0, 1, 2, 3, 4, 5, 6, 7] and range will keep cycling values in that list forever. The izip function then pairs that 0-7 cycle with the data.

Conclusion

These are just a couple of instances where we can eliminate the if statements and make the code shorter, faster, and simpler to understand.

3 thoughts on “Eliminate If from Your Code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s