Top 7 Python One-Liners that makes you feel like a God

Top 7 Python One-Liners that makes you feel like a God

Reason to switch from c++ or java to python

Python

Python is a high-level programming language that sometimes makes you feel like God. Now you may be curious to know how python can make you feel like a God. Python does it by converting more than 5 lines of code to 1 line with its one-liner ability. Python syntax is also the easiest syntax which gets rid of the messy semi-colon that we often forget to insert at the end of the statement and we get scolded by the compiler for it.

Now let me elaborate on the massive power of python with one-liners:-

1) Swap 2 variables

We can swap 2 variables without the need for a third temporary variable and it's quite an awesome and useful tip.

#before swapping
a=5
b=10
print(a,b)

#after swapping
a,b=b,a
print(a,b)

2) List Comprehension

We can create a list in one line with the help of list comprehension instead of writing a For Loop.

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

#list comprehension
squares=[i*i for i in range(10) if i % 2 == 0]
print(squares)

Screenshot from 2022-12-03 18-31-47.png

3) if-else (ternary operator)

We can create an if-else statement in one line with the help of a ternary operator.It stores 42 in var if 3 is greater 2 else stores 99 in var if 3 is not greater than 2 in this example.

var = 42 if 3 > 2 else 99
print(var)

4) Print only elements of the list

We can print only elements of a list in one line instead of applying for loop to achieve it with the (*) operator.

lst = [1,2,3,4,5,6]
print(lst) # without * operator
print(*lst) # with * operator

5) Reverse a list

You can reverse a list with this slicing which is a one-liner and you can use this to find whether the list is palindrome or not. It can work with string too. You can try it out yourself for string

ls = [1,2,3,4,5,6]
print(ls) #normal
print(ls[::-1]) #reverse

6) Space-separated numbers to integer list.

This is quite a useful method that saves a lot of time while solving problems using python. In this code snippet, we first converted the string numbers to integers using a map and then converted the complete series to a python list.

strg = "1 2 3 4 5 6"
lst = list(map(int,strg.split()))
print(lst)

7) Number of days left in a year

This one-liner tells you how many days are left in a year with just one line and it is very useful.

import datetime;print((datetime.date(2022,12,31)-datetime.date.today()))

8) Read the file in the list

We can read a file in the list using a one-liner and it can save you a lot of time while working with different files.

Let we have a sentence.txt file.

Its
Okay
is
best
sentence 
to 
console

Let's read this file with a one-liner in python.

sentence = [line.strip() for line in open("sentence.txt","r")]
print(sentence)