Powerful Python one-liners to look like a pro

Feature image

Python is an amazing and versatile programming language that is very easy to learn and work with. Like many programming languages, it offers more than one way to solve a problem, some requiring more lines of code than others.

Now, fewer lines of code is not always the best answer, as sometimes we may clutter our algorithms and make them hard to read and understand, but when done right, it increases the quality of your code.

Python as a programming language is extremely good at this, reason why it is so often the favorite choice for coding challenges, interviews, and the likes.

Today, we will learn a few snippets and tricks you can use to solve everyday operations into a single line of code, going from the very simple to some more advanced techniques.


Single if-else condition

First stop, conditionals. Conditionals are great, and they are a fundamental control flow statement. Still, they can sometimes be a bit chunky, extending for multiple lines even when we want to do something simple with them. Fortunately, there’s another way with Python.

Let’s see what we mean with an example:

x = 10
y = 5
if x > y:
    print("x is greater than y")
else:
    print("y is greater than x")

Quite a few lines of code, now, how can we simplify it with Python?

x = 10
y = 5
print("x is greater than y" if x > y else "y is greater than x")

Pretty much like in the English language, you can form an if statement in a one-liner using the following structure:

<conditional-true> if conditional else <conditional-false>

Multiple if-else conditions

Sometimes we use many of the if-else statements, and we use the elif keyword, which is an abbreviation for else if keywords together and this kind is a little bit complicated to convert to a one-liner python code but let’s first see an example using elif inside your code:

x = 200
if x < 20:
    print("x is less than 20")
elif x == 200:
    print("x is equal to 200")
else:
    print("x is above 20")

The code will print the second statement, which is “x is equal to 200” and let’s now convert this code into one line of code:

x = 200
print("x is less than 20") if x < 20 else print("x is equal to 200") if x == 200 else print("x is above 20")

This is using the same trick as before, just extending it to multiple conditions. You have to be careful, though. It can become tough to read very fast, so evaluate what’s best for your use case.


Assign multiple variables

Simple as it sounds, we can declare multiple variables in Python by assigning different values and even data types to each variable on a single line. Here is how it looks like:

name, age, single = jc, 35, False

List comprehensions

List comprehensions are a friendly and elegant way to define and create new lists based on existing lists, and they are one of the best things in Python.

Let’s take an example of generating an array with a sequential number from 0 to 4:

scores = []
for x in range (5):
    scores.append(x)
print(scores)

The same result we can achieve using list comprehensions:

scores = [x for x in range(5)]
print(scores)

Wow, such elegance! No wonder I enjoy working with Python so much.


Conditionals in list comprehensions

We just learned how to create list comprehensions by mapping every item on the original list into a new one, but what if we would like to skip some items based on a condition? For example, what if we only want odd numbers?

Let’s take a look at how that would look like, in multiple lines:

scores = []
for x in range (20):
    if x % 2 == 1:
       scores.append(x)
print(scores)

Now the same using conditionals in list comprehensions:

scores = [x for x in range(20) if x % 2 == 1]
print(scores)

Bonus: not only can list comprehensions be much cleaner, but they also perform much better than single loops, if not always in most cases.


Swapping variables

You probably learned about the variable switching problem if you ever studied in college or even in some code camps or books. A third variable (a temporary variable) is required to make the switch. It usually goes something like this:

tmp = var1
var1 = var2
var2 = tmp

Now, in Python, you can also do it directly in one statement:

var1, var2 = var2, var1

Even further, you can use this same technique to switch elements in an array

colors = ['red', 'green', 'blue']
colors[0], colors[1] = colors[1], colors[0]
print(colors)

#-------------------
# Output
#-------------------
['green', 'red', 'blue']

Nested loops in list comprehensions

List comprehensions work well on a list, but how about a matrix? Or lists of lists?, no problem at all, and the syntax stays very clean and elegant:

my_list = [(x, y) for x in [3, 4, 6] for y in [3, 4, 7] if x != y]
print(my_list)

#-------------------
# Output
#-------------------
[(3, 4), (3, 7), (4, 3), (4, 7), (6, 3), (6, 4), (6, 7)]

Dictionary comprehension

The same concept as with list comprehension but for dictionaries, let’s make a new example, we need a key/value pair, where the value is the key squared.

square_dict = dict()
for num in range(1, 11):
    square_dict[num] = num * num
print(square_dict)

And using dictionary comprehensions:

square_dict = { num: num * num for num in range(1, 11) }
print(square_dict)

Flatten a list

Data scientists work a lot with lists and multi-dimensional data, and sometimes they need to convert the multi-dimensional list into one-dimensional. They often use packages like numpy to do it. The example below shows you how to perform the same action using a pure Python one-liner:

my_list = [[1,2], [4, 6], [8, 10]]
flattened = [i for j in my_list for i in j]
print(flattened)

#-------------------
# Output
#-------------------
[1, 2, 4, 6, 8, 10]

As you may have realized, this example is just an application of list comprehensions.


Deconstructing variables from lists

Let’s say you have a list, and you want to capture some of its values into variables and all the rest as a list. This can come in handy when dealing with arguments. Let’s see an example

x, y, *z = [1, 2, 3, 4, 5]

print(x, y, z)

#---------------------
# Output
#---------------------
1 2 [3, 4, 5]

Load file into a list

An often simple task that is required for scripting is to work with files, in particular, reading files into lists, so that we can perform operations on the data.

With Python, we can read a file into a list with a simple list comprehension and in just a single line.

my_list = [line.strip() for line in open('countries.txt', 'r')]
print(my_list)

Conclusion

Python is fantastic! Today we learned some cool Python tricks to write more elegant, simple, and more efficient code. But it doesn’t stop here. We just show you a few scenarios and options, but there’s much more Python has to offer, and I invite you to discover more. And when you do, please let me know, share with me in the comments section below or ping me on twitter .

Thanks for reading!