Ternary Conditional Operators in Python

Mastering Efficient List and Dictionary Comprehension

Photo by Belinda Fewings on Unsplash

Python is versatile to use and its goal is to make development easier for the user. Compared to C# or Java which are notoriously cumbersome to master, Python is relatively easy to get good at. Moreover, it’s relatively easy to get pretty damn good at.

List and Dictionary Comprehension are widely used methods but something I find that’s a bit less used (especially by beginners) is the Ternary Conditional Operator. The method really streamlines your code and makes it both visually and economically better to run and deal with. Just don’t make it too complicated!

They’re pretty easy to get your head around, so let’s get into it.


Ternary Conditional Operators

The rationale behind these operators is quite simple. Beforehand, if you had an if-else type of problem, you would have to write the following pretty chunky piece of code:

if np.random.rand()>0.5:
x = a
else:
x = b

However, we’re all so familiar with this paradigm and it’s used so often, surely there must be a quicker way? With Ternary Conditional Operators, we can condense the code to the following:

x = 1 if np.random.rand()>0.5 else 0

Which, as in the first statement, computes that if the condition is True, then x=1, otherwise, x=0.

Pretty easy right?


List (and Dictionary) Comprehension with Ternary Conditional Operators

Most people who use Python are familiar with List comprehension. List comprehension is an elegant way to define and create lists based on existing lists.

Say we wanted to do a function to every item in a list (very common problem!). An un-elegant way to do it would be as follows:

new_array = []
for x in array:
new_array.append(custom_function(x))

With a list comprehension, this can be made a lot more efficient as follows:

new_array = [custom_function(x) for x in array]

But quite often, the problem may be a little bit more complicated, so for that, we could look towards the Ternary Conditional Operator.

So take the following problem where we loop through a list of items in an array and given a condition, we set a new value for each item:

new_array = [] # Define a new array
for x in random_array: # Loop over the list
if x > 0.5: # Condition
new_array.append(1) # Result One
else: # Otherwise...
new_array.append(0) # Result Two

This can then be efficiently condensed to the following:

new_array = [1 if x>0.5 else 0 for x in random_array]

See how much easier and efficient that is?

Likewise (and for added bonus points), I now provide the example code for a Dictionary Comprehension with a Ternary Conditional Operator. Here we are simply creating some form of a mapping dictionary which is 1 if an item in Z is in Y, and a 0 otherwise:

Y = ['h','e','l','l','o']
Z = ['a','e','i','o','u']
new_dict = {x:1 if x in Y else 0 for x in Z}

where new_dict now looks like the following:

{‘a’: 0, ‘e’: 1, ‘i’: 0, ‘o’: 1, ‘u’: 0}

Ta da! Super quick, easy, and clean!

You can see that the code is so much tidier as you contain the problem into a pretty elegant one liner, not to mention the reduced amount of headaches and comments you would have to have done before.

Photo by Pineapple Supply Co. on Unsplash

Coding efficiently is the whole point of Python. It’s not the fastest language (44 times slower than C#) or the most widely used (debatably JavaScript), so with this design ethos in mind, it’s worthwhile to make your code as readable as possible.

Methods like Ternary Conditional Operators and List Comprehensions make your job as a Researcher or Scientist 100x easier because you can just fly through your research.

For me, my research process usually involves a few steps and each one can be small and significant. Ensuring that your code is airtight and efficient is by far the best method in being able to focus on the bigger picture, and getting bogged down in massive amounts of code.

I would definitely encourage you to use this method!


Thanks again! Please message me if you have any questions, always happy to help!

Keep up to date with my latest work here!

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: