Elegant Python One-Liners

Introduction

Drunk3n-d3v
5 min readSep 5, 2021

Hello friends it’s me Drunk3n-d3v, hopefully am not talking to an imaginary audience. I have finally decided to elude the obscurity of my existence. Today I will talk about elegant pythonic one liners, that can assist in making our python code poetic.

Before then, it is necessary to note that a block of code is pythonic if it makes use of idiomatic ideas and expressions that are specific and only understandable by the python interpreter and pythonistas (python developers). In a much broader sense, consider the following example:

In [1]: a,b,c = [2,3,4]
In [2]: print(a,b,c)

An experienced developer who probably may know a variety of programming languages but python, may boldly say that the above array unpacks to:

2 3 4

And thus declares the challenge as trivial, but don’t worry pythonistas, we have a trap for him. Now push this next challenge to him:

In [3]: a, *b, c, d = [2,3,4,5,6,7,8,9]

He raises an alarm that the code will not run, because the array has more elements on the RHS, than the variables on the LHS. But you as a pythonista, knows that the code runs beautifully because it is pythonic (specific to and understandable to both the interpreter and the python developer). The array therefore unpacks to(we’ll talk more on this later):

2 [3, 4, 5, 6, 7] 8 9

Having laid the foundation of what we mean by pythonic code, let us now discuss some pythonic idioms that can make our code succinct.

Assignment (“=”) and Boolean Operators:

Consider a simple case of the problem where the name field of a questionnaire form is not required to be processed with an empty string, but we don’t want to force the people filling the form to enter their name(probably they value their privacy). So we have decided, if the field come blank, we would replace it with a default value, say ‘Anonymous’.

In general the solution that comes to mind would be similar to:

What’s the interpreter doing here?

When the interpreter gets to line 12, since the RHS of the assignment operator is evaluated first, the interpreter first checks if the first operand evaluates to True(True here could mean the boolean value ‘True’ or a non empty sequence or a non zero value or a non empty mapping), it doesn’t bother to check if the second operand evalautes to True(if it was an ‘and’ operator and the first operand evalautes to False, it also never checks the second operand, otherwise it does). If it evaluates to True, it simply assigns the value to the variable on the LHS, ‘name’ in this case otherwise it assigns the second operand. Now in our case, we can see that if we pass an empty string to name then the interpreter assigns the second operand, since an empty string has a truth value of False, but if a non empty string is passed to name, the interpreter simply assign that value to the LHS without checking the second operand. In general, this technique of skipping the second operand by the interpreter when the first operand evaluates to True(in an ‘or’ expression) or False(in a ‘and’ expression) is called “Short Circuit or Lazy evaluation”.

There is more:

This pythonic idiom can also help us side step errors sometimes; Consider the problem, where you are to always return the maximum value of an array of positive integers or a default value(say 0) if the array is empty, we could have the following solutions:

Iterables

An iterable is any object that can be iterated over, that is an object capable of returning its members one at a time. In fact objects of any classes that has the __iter__() method or a __getitem__() method implemented on it is an iterable. Example includes your lists, strings, tuples, sets, dictionaries etc. Let’s start with this simple example:

To swap two numbers a and b, one might do the following

Also, given an iterable we can unpack its values into several variables in a pythonic way. For example if we intend to assign the elements of an iterable to some variables, we can simply do the following:

Taking it a bit forward, we can unpack iterables with more elements to fewer variables by assigning some slice of the iterable to a single variable as shown below:

What is the interpreter doing?

The variables without the asterisks (‘*’) are called the mandatory targets, while the one with ‘*’ is called the stared expression(as it defines a subexpression that will be assigned a list of all items from the iterable being unpacked, that are not in assigned to any of the mandatory targets). Now considering the expression on line 1(in the above code), the interpreter first collects all items for the mandatory targets that are before the starred one (in this case the value of ‘a’) and then collect all remaining items from the iterable in a list (in this case *b, c values are in the remaining list) and then pop items for the mandatory target that are after the starred expression(in this case the value of ‘c’) from the list.Then finally, it pushes the single items and the resized list onto the stack.It is necessary to note that there can only be one starred variable during the unpacking and the length of the iterable must at least be equal to the number of mandatory targets.

Now we would talk about list comprehension and generator expression.

List comprehension basically involves the generation of a list at runtime with a for loop instead of the common append method, while a generator expression basically involves the generation of an iterator, which does not dump all its element like in list comprehension but yields them(that is returns each of them one at time), making generator expressions memory efficient when compared to list comprehension. Now suppose we are to return odd numbers less than 100, we can do this as follows:

another example using these techniques would be in the cartesian product of two or more lists:

Listcomps generates lists, while the genexps can be used to initialize tuples, arrays, and other types of sequences. Both use the same syntax as listcomps, but genexps are enclosed in parentheses rather than brackets. There is also dict comprehension which would be discussed in the next part.

Conditional Expressions

Conditional expression in python is similar to the tenary operation in C/C++ (where you make use of the ‘?’ and ‘:’ operators) but in python the conditional expression is of the form:

<expression1> if <condition> else <expression2>

so what happens is that the interpreter first checks the ‘if condition’, if it evaluates to True, then it evaluates expression1 otherwise expression2 is evaluated. Consider the example to print the maximum of two numbers.

Conclusively, these elegant pythonic idioms can assist in making our code succinct and readable. We shall give an in-depth discussion on dictionaries in the next part. If you have other pythonic one-liners that you use frequently, you can add them in the comments below. Happy reading!!!

--

--