DEV Community

Cover image for 18 Python one-liners that will speed up your coding process.
Yash Makan
Yash Makan

Posted on • Updated on

18 Python one-liners that will speed up your coding process.

Please don't use these one liners in any interview, or in any production based code. The article is just for fun seeing the replacement of some programs/code block in one line. Some like list comprehension is a must know as well.

Hi folks, I am Yash Makan and in today's blog, we are going to talk about one-liners in python. I clearly remember when I chose to learn python it was just because of the simplicity and readability. But you know what you can make the python code even more easy with less lines of code. Yup! thats right my friend. These one-liner code can save you a lot of time, memory and can impress your friends...

https://media3.giphy.com/media/Bvo7iDxInexT0oCHgg/giphy.gif?cid=ecf05e47oy9b0df2af0v2j9pw2tpnog57mkdyzdd42he0y6s&rid=giphy.gif&ct=g

what is a one-liner code?

You can think of one-liner code as a block of code compressed together so that it fits inside one line. It is the concise, useful programs packed in just one single line.

why do I need them?

So if you are not a big fan of writing one-liners or you are just curious that why do I have to know these then below are some pretty convincing topics.

  • Understanding One-liners will make a python expert as you will get a much better understanding of the language.
  • This will help you to write the code faster. You can write the piece of code much faster than others which will help you in competitive programming.
  • On-liners will improve your basics and roots of programming as they strengthen your basics.
  • You will write the code more in a pythonic way. Generally, people who come from different languages often write code in an un-pythonic way in python for example they don't use list comprehension, multiple assignments, and slicing etc.
  • You can impress your friends, colleagues and you can give a good impression in your interview if you have a good grasp of one-liners.

But also it can be a little hard as well. Imagine programming as chess. You know the basics is like knowing what is variables, loops, conditions, data structures, classes but learning the master movies and creating your own strategy is like one-liners. In the beginning, it can be hard and quite overwhelming but once you get to know them. You can achieve greatness and win matches faster than a lot of other players. Everything has a price to pay my friend...

Basics

1. If-else

Before

if 3 < 2:
    var=21
else:
    var=42
Enter fullscreen mode Exit fullscreen mode

After

var = 21 if 3<2 else 42
Enter fullscreen mode Exit fullscreen mode

2. Elif

Before

>>> x = 42
>>> if x > 42:
>>>     print("no")
>>> elif x == 42:
>>>     print("yes")
>>> else:
>>>     print("maybe")
yes
Enter fullscreen mode Exit fullscreen mode

After

>>> print("no") if x > 42 else print("yes") if x == 42 else print("maybe")
yes
Enter fullscreen mode Exit fullscreen mode

3. If without else

Before

condition = True

if condition:
    print('hi')
Enter fullscreen mode Exit fullscreen mode

After

if condition: print('hello')
print('hello') if condition else None
Enter fullscreen mode Exit fullscreen mode

4. Function

Before

def f(x):
    return "hello "+ x
Enter fullscreen mode Exit fullscreen mode

After

f = lambda x: "hello "+ x
f = exec("def f(x):\n    return 'hello '+ x")
Enter fullscreen mode Exit fullscreen mode

5. Loop(list comprehension)

Before

squares = []
for i in range(10):
    squares.append(i**2)
Enter fullscreen mode Exit fullscreen mode

After

squares=[i**2 for i in range(10)]
Enter fullscreen mode Exit fullscreen mode

6. Loop with If

Before

squares = []
for i in range(10):
    if i%2==0:
        squares.append(i**2)
Enter fullscreen mode Exit fullscreen mode

After

squares = [i**2 for i in range(10) if i%2==0]
Enter fullscreen mode Exit fullscreen mode

7. Loop with if else

Before

squares = []
for i in range(10):
    if i%2==0:
        squares.append(i**2)
    else:
        squares.append(False)
Enter fullscreen mode Exit fullscreen mode

After

squares = [i**2 if i%2==0 else False for i in range(10)]
Enter fullscreen mode Exit fullscreen mode

8. While Loop with if else

Before

c=0
while c < 10:
    if c!=5:
        print(c)
    else:
        print("FIVE")
    c+=1
Enter fullscreen mode Exit fullscreen mode

After

while c < 10: c+=1; print(c) if c!=5 else print("FIVE")
Enter fullscreen mode Exit fullscreen mode

9. swap variables

Before

>>> def swap(x,y):
    x = x ^ y
    y = x ^ y
    x = x ^ y
    return x, y
>>> swap(10,20)
(20,10)
Enter fullscreen mode Exit fullscreen mode

After

>>> x, y = 10, 20
>>> x, y = y, x
(20, 10)
Enter fullscreen mode Exit fullscreen mode

10. Multiple Assignment

Before

a="ONE"
b=2
c=3.001
Enter fullscreen mode Exit fullscreen mode

After

a, b, c = "One", 2, 3.001
Enter fullscreen mode Exit fullscreen mode

11. Write String In File

Before

text = "Helllloooooo"
fileName = "hello.txt"
f=open(fileName, "a")
f.write(text)
f.close()
Enter fullscreen mode Exit fullscreen mode

After

text = "Helllloooooo"
fileName = "hello.txt"
print(text, file=open(fileName, 'a'))
Enter fullscreen mode Exit fullscreen mode

12.Quicksort

Before

# Source - https://stackabuse.com/quicksort-in-python/

def partition(array, start, end):
    pivot = array[start]
    low = start + 1
    high = end

    while True:
        while low <= high and array[high] >= pivot:
            high = high - 1

        while low <= high and array[low] <= pivot:
            low = low + 1

        if low <= high:
            array[low], array[high] = array[high], array[low]
        else:
            break

    array[start], array[high] = array[high], array[start]

    return high

def quick_sort(array, start, end):
    if start >= end:
        return

    p = partition(array, start, end)
    quick_sort(array, start, p-1)
    quick_sort(array, p+1, end)

array = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]

quick_sort(array, 0, len(array) - 1)
print(array)
Enter fullscreen mode Exit fullscreen mode

After

array = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]
q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []
print(q(array))
Enter fullscreen mode Exit fullscreen mode

13. Fibonacci

Before

def fib(x):
    if x <= 2:
        return 1
    return fib(x - 1) + fib(x - 2)
Enter fullscreen mode Exit fullscreen mode

After

fib=lambda x: x if x<=1 else fib(x-1) + fib(x-2)
Enter fullscreen mode Exit fullscreen mode

14. HTTP Server

Before

import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
Enter fullscreen mode Exit fullscreen mode

After

python -m http.server 8000
Enter fullscreen mode Exit fullscreen mode

15. Nested For Loops

Before

iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']
for x in iter1:
    for y in iter2:
        print(x, y)
Enter fullscreen mode Exit fullscreen mode

After

[print(x, y) for x in iter1 for y in iter2]
Enter fullscreen mode Exit fullscreen mode

16. Print Without Newline

Before

for i in range(1,5):
    print(i, end=" ")
Enter fullscreen mode Exit fullscreen mode

After

print(*range(1,5))
Enter fullscreen mode Exit fullscreen mode

17. Class

Before

class School(): 
    fun = {}
Enter fullscreen mode Exit fullscreen mode

After

School = type('School', (object,), {'fun':{}})
Enter fullscreen mode Exit fullscreen mode

18. Walrus:= (Python 3.8)

Before

command = input("> ")
while command != "quit":
    print("You entered:", command)
Enter fullscreen mode Exit fullscreen mode

After

while (command := input("> ")) != "quit": print("You entered:", command)
Enter fullscreen mode Exit fullscreen mode

Conclusion

So now you have some understanding of python one-liners and this will help to speed up your coding process. I hope that you've learnt something new from this article as I myself get to know some cool tricks and one-liners that I didn't know earlier. If this is the case with you as well then do click the heart button when increases my motivation(1 like = 1 good karma). Also, share the post with your friends so that they too can learn something new(don't be selfish...). Hope to be in your mind again, till then b-bye!

https://media4.giphy.com/media/w89ak63KNl0nJl80ig/giphy.gif?cid=ecf05e478g5vv310sx1w5035xnuj17tgxbdtlcpcvas5fsoj&rid=giphy.gif&ct=g

Other Articles

Socials

Discussion (28)

Collapse
darkwiiplayer profile image
DarkWiiPlayer

This will help you to write the code faster. You can write the piece of code much faster than others which will help you in competitive programming.

Any programmer that is mainly limited by their typing speed should seriously consider a career change.

Collapse
evanilukhin profile image
Ivan Ilyukhin

In competitive programming, every second matters. But, yes, in production these fragments are not acceptable. Readability of a codebase is much more important.

Collapse
adinar profile image
AdiNar

Great idea for an article. 11 and 14 seem quite interesting. However:

You can impress your friends, colleagues and you can give a good impression in your interview if you have a good grasp of one-liners.

At least 2,4,8,12,13 and 17 are absolute no-go for an interview. You can impress your friends with them, but never ever use them again.

You should consider removing them from the article or mark them somehow. Experienced developer will just laugh at it, begginer may learn a bad habit.

Collapse
zrsmithson profile image
zrsmithson

Yeh, pretty much anything here that has a colon is an unreadable, worthless one liner, except maybe for helping copy/paste to run it with python -c "bad_one_liner; some_other_function()

And anything that tries to take advantage of a list comprehension or conditional/ternary assignment for the side effects, like 2 and 15, makes me cringe hard.

Though these can arguably fixed and can even be useful for long expressions, especially when used to the extra whitespace of the black formatter. Interestingly with things like this, it is often only readable with long variable names that force line splits. Each proposed alternative will be copied as a one-liner at the end.

2. Honestly chaining conditional assignments just looks bad, but at least this actually uses expressions and doesn't rely on side effects.

print(
    "no"
    if x > 42
    else "yes"
    if x == 42
    else "maybe"
)
Enter fullscreen mode Exit fullscreen mode

And for good measure, here is an interesting yet even less readable way. You don't even need the inner parens, but then its even worse.

print(
    (x > 42 and "no")
    or (x == 42 and "yes")
    or "maybe"
) 
Enter fullscreen mode Exit fullscreen mode

15. Thinking about which is the outer and inner loop makes anything like this a bit awkward

print(
    *[
        f"{x} {y}"
        for x in iter1
        for y in iter2
    ],
    sep="\n"
) 
Enter fullscreen mode Exit fullscreen mode

Alternatively, using "".join()

print(
    "\n".join(
        f"{x} {y}"
        for x in iter1
        for y in iter2
    )
) 
Enter fullscreen mode Exit fullscreen mode

In this case you can use itertools.product which might make it clear that youre iterating over the cartesian product, instead of having to mentally unwrap a nested for loop

from itertools import product
print(
    *[
        f"{x} {y}"
        for x, y in product(iter1, iter2)
    ],
    sep="\n"
) 
Enter fullscreen mode Exit fullscreen mode

As promised, each as a one-liner. Im not sure I did anything to improve readability.

2.

print("no" if x > 42 else "yes" if x == 42 else "maybe")
print((x > 42 and "no") or (x == 42 and "yes") or "maybe") 
Enter fullscreen mode Exit fullscreen mode

15.

print(*[f"{x} {y}" for x in iter1 for y in iter2], sep="\n")
print("\n".join(f"{x} {y}" for x in iter1 for y in iter2))

print(*[f"{x} {y}" for x, y in product(iter1, iter2)], sep="\n")
print("\n".join(f"{x} {y}" for x, y in product(iter1, iter2)))
Enter fullscreen mode Exit fullscreen mode
Collapse
yash_makan profile image
Yash Makan Author

Thanks for reading!

Collapse
amal profile image
Amal Shaji

Do not assign a lambda expression, use a def (E731). Most of these one-liners will be flagged by code quality tools.

Collapse
thomasjunkos profile image
Thomas Junkツ • Edited on

The thing with clever code is: Most of the time you have to be twice as clever to debug it than to write it.

So don't be too clever when writing it and give yourself a chance of debugging it in the future.

Collapse
xtofl profile image
xtofl

Worse: everybody coming after you has to be. Of course, OP warned us in the introduction :).

Collapse
hmorris94 profile image
Hunter Morris

Interesting post! At work, I'm often just looking for quick ways to parse a one-off dataset or other small things like that, and it doesn't have to be readable or maintained by anyone but myself, so I use several of these (admittedly non-Pythonic) schemes. Writing for a team is different. This is still quite useful, especially to learn the extent of some of the nuanced features that this language has. Cheers.

print(*range(1,5)) didn't work for me (running Python 3.10), but Walrus:= taught me a new trick and I will definitely be using it.

Collapse
yash_makan profile image
Yash Makan Author

Glad I could help. Thanks for reading

Collapse
smichaele profile image
Stephen J. Michaele

The article isn't offensive, Yash. Much of it just doesn't represent good coding practices so I'm glad you added the note at the top. As professional developers we need to be careful what advice we give to those with less experience. Keep sharing!

Collapse
yash_makan profile image
Yash Makan Author

Yes! I agree with you. Thanks

Collapse
yash_makan profile image
Yash Makan Author

I have added a note on the top of the Article to not use these one liner in any production based projects as the code becomes less readable. The article is just for exploring different ways of reducing the code size and for fun... If anybody is offended by the article then I am sorry and will take care of this in my future articles
Thanks

Collapse
matthewsalerno profile image
matthew-salerno

These are certainly some dangerous tools, and I'm bound to misuse them in the future just I have in the past. However, that doesn't mean it's not worth exploring. I find some one liners easier to follow than more verbose versions, and the conciseness can be especially helpful as well. In practice, I don't think one liners have as much to do with compactness and readability as it is about how you approach the problem. Sometimes problems are easier to think about in a more mathematical sense, such as graph traversal or parsing. When this happens I find the conciseness of one liners very helpful. Likely because most of the tools that enable them were borrowed from functional languages like Haskell.
Admittedly, my hipster impulse to abuse the most obscure parts of a language does not make good code, at best it makes fun code. So maybe take what I say with a grain of salt.

Collapse
cappe987 profile image
Casper

Others have already pointed out that a lot of these are bad ideas, I would like to add one thing. While ternary if's, list comprehension and lambdas are cool, they are not equivalent to their regular variants. Once you have an if-statement with two statements inside it you can no longer convert it into a ternary. Same applies to list comprehension and lambdas. They are all basically simpler and more restricted versions of the regular variants, and have a more specific use-case. If you do not know when to use them it is better to avoid them rather than trying to squeeze them in wherever possible.

Collapse
thumbone profile image
Bernd Wechner

If you're going to toy with one-liners like this and justify it on the basis of learning (as most of these are not good practice as others have noted) then I'd suggest you add a little explanatory commentary to the one-liners. I mean for example a few of them are just standard list comprehensions but you don't mention that anywhere and that's a useful piece of vocabulary for a wannabe Python coder and you could group those under an embracing heading of "list comprehensions".

Just a thought.

Collapse
yash_makan profile image
Yash Makan Author

Thanks for the note advice. Added the quote on top.

Collapse
elvi2 profile image
ElVi2

As someone who used these in the past during her studies, I personally would say that while they make the code more compact, depending on the situation they may also potentially compromise debugging and overall readability, especially if one uses a lot of them (I got a lot of complaints from teachers about my code being hard to follow when I was using a lot of one-line loops and had to rewrite them on spot). So I think at least a few of these are pretty situational IMO.

Collapse
coderhax profile image
coderhax

Great 😃👍

Collapse
yash_makan profile image
Yash Makan Author

Thanks for reading! 😊

Collapse
salabim profile image
salabim

Example 2 can be written more compact:
print("no", "maybe", "yes")[(x < 42) -(x > 42) + 1]
, which is arguably easier to read.

Collapse
rostemelov profile image
Rostemelov

Really helpful for a noob like me... Thanks 😊👍

Collapse
yash_makan profile image
Yash Makan Author

We are all learning @rostemelov . Thanks for reading...

Collapse
t_rakibul profile image
Md. Rakibul Islam

Great article 👌👍.
Thanks 😊

Collapse
yash_makan profile image
Yash Makan Author

Glad I could help!

Collapse
machinesrental profile image
machinesrental

When I see this hardly readable code, I like Typescript much more than before 😎

Collapse
darkwiiplayer profile image
DarkWiiPlayer

You just agreed with me though. I'm confused.