Powerful Python one-liners to look like a pro

Python is a fantastic and versatile programming language that is simple to learn and use. It, like many other programming languages, provides multiple solutions to a problem, some of which require more lines of code than others.

Now, having less lines of code isn’t always the ideal solution, as it can clutter our algorithms and make them difficult to read and understand, but when done correctly, it can improve 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.


Sum of digits of a number

We use mathematical operators like % (modulo) and / division to get the sum of a number’s digits. In Python, however, we can calculate the sum using just one line of code.

This one-liner is useful for finding the sum of digits of a number.

sum_of_digit = lambda x: sum(map(int, str(x)))output = sum_of_digit(123)
print("Sum of the digits is: ", output)Output:
Sum of the digits is: 6

Single if-else condition

First and probably most important, conditionals. Conditionals are fantastic, and they’re an important part of any control flow statement. Even when we wish to accomplish something basic with them, they might be a bit hefty at times, extending for numerous lines. Fortunately, Python offers an alternative.

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

We sometimes use a lot of if-else statements, and we use the elif keyword, which is an abbreviation for else if keywords combined, and this is a little more difficult to convert to a one-liner python code, but first let’s look at an example of 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.


Reverse a string

This code is useful for finding the reverse of a string. We use string slicing to find the reverse in a single line of code.

input_string = "Namaste World!"
reversed_string = input_string[::-1]print("Reversed string is: ", reversed_string)Output:
Reversed string is: !dlroW etsamaN

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 simple and elegant way to define and generate new lists from existing ones, and they are one of Python’s greatest features.

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 learnt how to make list comprehensions by mapping each item from the original list to a new one, but what if we want to skip some items based on a condition? What if we only want odd numbers, for example?

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.


Fibonacci series

The Fibonacci series is a collection of numbers in which each number is the sum of the two numbers before it. In a single line of code, we generate a Fibonacci series using list comprehensions and a for loop.

n=10fib = [0,1]
[fib.append(fib[-2]+fib[-1]) for _ in range(n)]
print(fib)Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Merge two dictionaries

We can merge multiple dictionaries in a single line of code using (**) operator. We just need to pass the dictionaries along with (**)operator to a {}, and it will merge the dictionaries for us.

dictionary1 = {"name": "Joy", "age": 25}
dictionary2 = {"name": "Joy", "city": "New York"} merged_dict = {**dictionary1, **dictionary2}
print("Merged dictionary:", merged_dict)
Output:Merged dictionary: {'name': 'Joy', 'age': 25, 'city': 'New York'}

Swap Keys and Values in a dictionary

This one-liner code is useful for swapping the key-value pairs of a dictionary.

dict = {'Name': 'Joy', 'Age': 25, 'Language':'Python'}result = {v:k for k, v in dict.items()}
print(result)Output:
{'Joy': 'Name', 25: 'Age', 'Python': 'Language'}

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 an amazing language! We learned several great Python tricks today that will help us develop more elegant, simple, and efficient code. But the story doesn’t end there. We’ve only covered a few cases and alternatives, but Python has a lot more to offer, and I encourage you to learn more.

Leave a Comment