18 Python one-liners that will speed up your coding process.
Tags: python, beginners, tutorial
Published: 2021-11-23 05:41:19

> 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](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

```python
if 3 < 2:
    var=21
else:
    var=42
```

After

```python
var = 21 if 3<2 else 42
```

### 2. Elif

Before

```python
>>> x = 42
>>> if x > 42:
>>>     print("no")
>>> elif x == 42:
>>>     print("yes")
>>> else:
>>>     print("maybe")
yes
```

After

```python
>>> print("no") if x > 42 else print("yes") if x == 42 else print("maybe")
yes
```

### 3. If without else

Before

```python
condition = True

if condition:
    print('hi')
```

After

```python
if condition: print('hello')
print('hello') if condition else None
```

### 4. Function

Before

```python
def f(x):
    return "hello "+ x
```

After

```python
f = lambda x: "hello "+ x
f = exec("def f(x):\n    return 'hello '+ x")
```

### 5. Loop(list comprehension)

Before

```python
squares = []
for i in range(10):
    squares.append(i**2)
```

After

```python
squares=[i**2 for i in range(10)]
```

### 6. Loop with If

Before

```python
squares = []
for i in range(10):
    if i%2==0:
        squares.append(i**2)
```

After

```python
squares = [i**2 for i in range(10) if i%2==0]
```

### 7. Loop with if else

Before

```python
squares = []
for i in range(10):
    if i%2==0:
        squares.append(i**2)
    else:
        squares.append(False)
```

After

```python
squares = [i**2 if i%2==0 else False for i in range(10)]
```

### 8. While Loop with if else

Before

```python
c=0
while c < 10:
    if c!=5:
        print(c)
    else:
        print("FIVE")
    c+=1
```

After

```python
while c < 10: c+=1; print(c) if c!=5 else print("FIVE")
```

### 9. swap variables

Before

```python
>>> def swap(x,y):
    x = x ^ y
    y = x ^ y
    x = x ^ y
    return x, y
>>> swap(10,20)
(20,10)
```

After

```python
>>> x, y = 10, 20
>>> x, y = y, x
(20, 10)
```

### 10. Multiple Assignment

Before

```python
a="ONE"
b=2
c=3.001
```

After

```python
a, b, c = "One", 2, 3.001
```

### 11. Write String In File

Before

```python
text = "Helllloooooo"
fileName = "hello.txt"
f=open(fileName, "a")
f.write(text)
f.close()
```

After

```python
text = "Helllloooooo"
fileName = "hello.txt"
print(text, file=open(fileName, 'a'))
```

### 12.Quicksort

Before

```python
# 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)
```

After

```python
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))
```

### 13. Fibonacci

Before

```python
def fib(x):
    if x <= 2:
        return 1
    return fib(x - 1) + fib(x - 2)
```

After

```python
fib=lambda x: x if x<=1 else fib(x-1) + fib(x-2)
```

### 14. HTTP Server

Before

```python
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()
```

After

```python
python -m http.server 8000
```

### 15. Nested For Loops

Before

```python
iter1 = [1, 2, 3, 4]
iter2 = ['a', 'b', 'c']
for x in iter1:
    for y in iter2:
        print(x, y)
```

After

```python
[print(x, y) for x in iter1 for y in iter2]
```

### 16. Print Without Newline

Before

```python
for i in range(1,5):
    print(i, end=" ")
```

After

```python
print(*range(1,5))
```

### 17. Class

Before

```python
class School(): 
    fun = {}
```

After

```python
School = type('School', (object,), {'fun':{}})
```

### 18. Walrus:= (Python 3.8)

Before

```python
command = input("> ")
while command != "quit":
    print("You entered:", command)
```

After

```python
while (command := input("> ")) != "quit": print("You entered:", command)
```

## 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](https://media4.giphy.com/media/w89ak63KNl0nJl80ig/giphy.gif?cid=ecf05e478g5vv310sx1w5035xnuj17tgxbdtlcpcvas5fsoj&rid=giphy.gif&ct=g)


## Other Articles
- [4 Free hosting platforms for python web app with step-by-step process](https://dev.to/yash_makan/4-best-python-web-app-hosting-services-for-freewith-complete-process-57nb)
- [AI bot that could answer your questions](https://dev.to/yash_makan/ai-bot-that-could-answer-any-questions-asked-gmn)
- [Generate your own favourite TV episode using python](https://dev.to/yash_makan/generate-your-own-favourite-tv-episode-using-python-1pb3)


## Socials

- [My Website](https://www.yashmakan.co.in/)
- [Twitter](https://twitter.com/Yash_Makan)
- [Banner](https://www.yashmakan.co.in/banner)