Ternary Conditional Operators in Python

Original article was published on Artificial Intelligence on Medium

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 headache and commenting you would have to have done before.

Photo by Pineapple Supply Co. on Unsplash