Python One-Liner Tutorial
IMayBeMe

Introduction

What are One-liners?

In a nutshell, python one-liners are just simply programs that are written in just 1 line. They often make use of things like list comprehensions and lambda functions.

Why use them?

No reason, really. In my opinion they should NOT be used in actual code and rather should serve as a fun way to learn other confusing concepts. As an example, lambda functions were quite difficult for me to understand as I really didn't see their use-case until I started writing a few one-liners which helped me understand that they are just essentially a condensed function.

Other than that, they also will help you think to conserve space in actual code when writing small components. For example, someone may write this code to split a string into an array:

This may work, but is wildly inefficient and can be condensed to this using list comprehension:

Easy, right? So in this tutorial, I will pretty much be covering everything related to these one-liners and will be going in-depth into stuff like list comprehension.

Topic 1 - List comprehension

List comprehension is designed to provide a shorter syntax when you want to create a new list/array using a for loop. One important thing to note is that item assignment is NOT supported with list comprehension as opposed to a for loop.

The general syntax for a list comprehension goes like this:

Note: this is not actual code and will output an error

So in the snippet of pseudo-code above, you can see that I have specifically written expression which if you remember from math, does NOT include and = sign. If you still confused, an expression is something like this, 1 + 3 or from a more code-based side 'hello'.upper().

To give a better visualization, here is an example:

Note: there is a 21 in the range function because for loops are none-inclusive

This program finds all the even numbers in between 1 and 20 and outputs their squares into a list.

The output would be:

In addition, list comprehension also supports conditionals such as if and else statements. Now you may be wondering what the difference is between if else statements and the example above. To put it simply, the difference is that the example above makes use of only the if statement and uses it to filter a list, similarly to the filter() function which I will get into later. The basic syntax of an if else statement with list comprehension would be:

To further elaborate, the structure of the if else works similarly to the human brain which often evaluates options as a string of instructions such as this: Do something if something is true, otherwise do something else. That quick example hopefully helped you understand the basic structure of if else and I have provided a code example below:

Note: if else statements in list comprehension do not support the use of pass and return

This would output:

Though that may be it for list comprehension I thought it would be important to add that python also has dictionary comprehension! I won't go too detailed into the specifics of it but the general syntax is:

As for the iterables part, you can iterate over two lists/arrays for example by using the zip() function which you can learn more about here. I also thought it would be good to provide a challenge to test your skills so here it is:

Create a list comprehension which iterates over a list which in this case will be, [2, -3, 7, 5, -4, 8] and outputs a new list which keeps all the positive numbers, and replaces the negative ones with 'negative'

Solution:

Topic 2 - Lambdas

You may have seen some jumbled code such as this, print(list(map(lambda x: x * 2, [1, 2, 3, 4]))) and wondered what it does. If so, in this section I will be going over all of that and you will have no problem reading code like that.

In a nutshell lambdas, are one-line/anonymous functions as the title of this tutorial suggests. They can be used with parameters like a normal function and do not require return as they will do it automatically once the expression is evaluated. Though lambdas may seem like a go-to replacement for functions they do come with some limitations which I have nicely displayed in the table below:

CategoryNormal FunctionsLambdas
NamingMust be namedCan be anonymous or named by using a var
Item AssignmentSupportedIs not supported just like list comp
Returning Valuesuse returnAutomatic Parameters
Use-caseAlmost everythingSpecific small expressions

So if you're still wondering about what lambdas actually look like, they come in two forms. The first one is anonymous:

The other option is to name it like this:

And this can be called just like standard functions:

Note: again, this is just the basic structure and will not output anything.

Ok so now that you have seen the basic structure of a lambda, I'll give you an example that will hopefully give you some context into how they work:

Output:

Now this is probably about as simple as a lambda will ever get, but it really does help to give you strong understanding of what the actual code looks like.

Right about now, I would recommend you to go and open up a repl and just mess around with named and unnamed lambdas just to get some hands-on practice.

The Map Function

Up until now, I have only really explained pure lambda functions which are quite limited in their functions and are probably something that you won't use that often. On the other hand, the map function can be used with lambdas to create amazing lambdas that can be used for a variety of purposes.

So to give you an understanding of the syntax here is the general structure of map():

Around now you may be wondering what map() actually does in practice. To put it simply, map() is used to apply a certain function to every item in a python iterable.

For example here is a program that multiplies every item in a list/array by two:

Note: you can also just call a normal function in the place of the lambda by using function_name(params)

You may be wondering why it is necessary to convert the result of the map function into a list. So to explain the map function normally would return something like this: <map object at 0x7f3d3d781c70> which as you can see is not very pleasing. So by using python's inbuilt list conversion method, we can actually get a usable output

The output of this would be as expected:

Map also supports the ability to pass a function on multiple iterables by doing the folowing:

This just simply multiplies the two lists together and provides the output:

The Filter Function

Filter() is an inbuilt python function that can be used to filter through an iterable as its name suggests. It is incredibly useful for filtering through lists and tuples and can be paired with lambdas effectively. Here is the general syntax:

Note: converting the result to a list is necessary just like the map function because filter() would normally return an object

Here is an an actual code example which filters through a list in python:

This will output:

There really isn't much more to the filter function than what I explained, so I will be moving on to the next part.

Topic 3 - Actually One Line

So by now, you may be wondering why this tutorial is called Python One-liners if all the code examples so far are actually two or maybe three lines. Now I could just give you my go-to answer and rant on about how all the logic and data manipulation is happening on one line and that the rest is just declaring variables and printing, but what fun would that be. I really shouldn't encourage this so here is a little disclaimer:

PLEASE DO NOT THIS IN PYTHON OF ALL LANGUAGES. POSSIBLE SIDE EFFECTS INCLUDE: HORRIBLE AND MESSY CODE, UNREADABLE VARIABLES, BEING DISGRACED IN THE PROGRAMMING COMUNITY

Now that I have finished my little disclaimer, here is the solution I was going to give you: python supports semi-colons

Pretty much this allows you to take perfectly nice code like this:

And turn it into this:

This may seem cool to do once or twice just to get the satisfaction of a one-line program, but don't overuse it. Also as this is a one line tutorial, here are some additional but non-recommended tips to make your code shorter:

If statements:

Can be condensed to:

Spaces:

Python's interpreter actually ignores spaces in the code and removes them and so can you:

Elif statments:

I really don't know why you would do this but you can just use another if:

Declaring Variables:

One line:

Topic 4 - Aditional Resources

My hands are getting tired now so I have just listed some extra resources to use in addition to this tutorial.

List Comprehension:

Lambdas:

Map Function:

Filter Function:

So that's it for this tutorial and I hoped you enjoyed. Please leave any feedback/suggestions in the comments!

You are viewing a single comment. View All
FlaminHotValdez

the table is...um...unaligned? :/

Other than that it's good(I just don't see why we would use this in real code!)

IMayBeMe

@FlaminHotValdez yeah the table didn’t render correctly but thecoder gave me a fix which I’ll add. As for not using it in code, I 100% agree with you and even put a small section at the top on that. I just feel like it’s a fun way to learn list comps and lambdas which actually are very useful