Make your python code shorter

Sriram Vasudevan
2 min readSep 24, 2021

When it comes to writing short codes, python is the first language that comes to our mind. The standard python syntax is itself shorter than other programming languages. This makes it easier on newbies to learn the language. Regardless of the code size, it does not compromise on functionality. In fact, in some cases, it is the most preferred language. But we can make the code even smaller.

Here are some ways one can make their python code shorter:

List comprehension or generators is the first thing that comes to mind when talking about code shortening. It is widely used and it cuts down the number of lines from >3 to 1. Here is an example of list comprehension in action:

List comprehension

Next one is called the unpacking operators. These are used to unpack iterable objects(single asterisk: *) and dictionaries(double asteriks: **). They eliminate a lot of unnecessary loops. Even though they are popularly referred to as the unpacking operators, they can also be use to pack objects into an iterable object.

Unpacking operator

Dictionaries are an excellent alternative for long if-else statements that contain functions that are called based on the user input. Once you get used to this, you might as bid adieu to if-else blocks. You can learn more about it here.

Using dictionaries to store functions

Many do not realize that functions calls can be nested inside other function calls. By using nested function calls, we can eliminate needless temporary variables which automatically shortens the code by a line.

Nested functions

The handy if-else statement can be condensed down to just one line. You can just blend the if-else block with the variable declaration part. This might look simple but it is actually very powerful. It can be used to implement if-elif-else blocks and nested if-elif-else blocks too!

Although these methods can be used to shorten your code, they offer little to no performance improvements and I would recommend you to follow the standard syntax that everyone can immediately understand. Always remember, code readability is critical, unlike the length of your code. Occasionally, python is preferred over other languages for code readability alone. Nevertheless, remember to have fun with the python syntactical playground.

--

--