50 python one-liners everyone should know

Photo by Nick Fewings on Unsplash

I was always amazed by how easily things can be done using python. Some of the tedious tasks can be done in a single line of code using python. I have gathered some of my favorite one-liners from python. I have listed out 50 of them below with an example for each.

from collections import Counter

s1 = 'below'
s2 = 'elbow'

print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')

or we can also do this using the sorted() method like this.

print('anagram') if sorted(s1) == sorted(s2) else print('not an anagram')
decimal = int('1010', 2)
print(decimal) #10
"Hi my name is Allwin".lower()
# 'hi my name is allwin'
"Hi my name is Allwin".casefold()
# 'hi my name is allwin'
"hi my name is Allwin".upper()
# 'HI MY NAME IS ALLWIN'
"convert string to bytes using encode method".encode()
# b'convert string to bytes using encode method'
import shutil; shutil.copyfile('source.txt', 'dest.txt')
qsort = lambda l : l if len(l)<=1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])
sum(range(0, n+1))

This is not efficient and we can do the same using the below formula.

sum_n = n*(n+1)//2
a,b = b,a
lambda x: x if x<=1 else fib(x-1) + fib(x-2)]
[item for sublist in main_list for item in sublist]
python3 -m http.server 8000
numbers[::-1]
import math; fact_5 = math.factorial(5)
even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]
# [2, 4]
# words = ['This', 'is', 'a', 'list', 'of', 'words']max(words, key=len)# 'words'
li = [num for num in range(0,100)]
# this will create a list of numbers from 0 to 99
num_set = { num for num in range(0,100)}
# this will create a set of numbers from 0 to 99
dict_numbers = {x:x*x for x in range(1,5) }
# {1: 1, 2: 4, 3: 9, 4: 16}
print("even") if 4%2==0 else print("odd")
while 1:0
isinstance(2, int)
isinstance("allwin", str)
isinstance([3,4,1997], list)
a=5
while a > 0: a = a - 1; print(a)
print("Hello, World!", file=open('file.txt', 'w'))
print("umbrella".count('l'))# 2
list1.extend(list2)# contents of list 2 will be added to the list1
dict1.update(dict2)
# contents of dictionary 2 will be added to the dictionary 1
set1.update(set2)
# contents of set2 will be copied to the set1
import time; print(time.time())
numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]
most_frequent_element = max(set(test_list), key=test_list.count)
# 4

However, this is not efficient and we can do the same using the collections module in a more efficient way like this.

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]

from collections import Counter
print(Counter(numbers).most_common()[0][0])
# 4
numbers = [[num] for num in range(10)]
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
print(int('30', 8)) 
# 24
dict(name='allwin', age=23)
quotient, remainder = divmod(4,5)
list(set([4, 4, 5, 5, 6]))

First, let us sort the list using the sorted() method. The sorted method will return the sorted list.

sorted([5, 2, 9, 1])# [1, 2, 5, 9]

Next, let us sort this using the sort() method. The sort() method will sort the original list and not return anything.

li = [5, 2, 9, 1]
li.sort()

print(li)
# 1, 2, 5, 9
sorted([5, 2, 9, 1], reverse=True)# [9, 5, 2, 1]
import string; print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
import string; print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
import string; print(string.digits)
# 0123456789
print(int('da9', 16))
# 3497
import time; print(time.ctime())
# Thu Aug 13 20:16:23 2020
list(map(int, ['1', '2', '3']))
# [1, 2, 3]
# {'one': 1, 'four': 4, 'eight': 8}
{key:d[key] for key in sorted(d.keys())}
# {'eight': 8, 'four': 4, 'one': 1}
# x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
# li = [1,2,3,4,5]# right to left
li[n:] + li[:n] # n is the no of rotations
li[2:] + li[:2]
[3, 4, 5, 1, 2]
# left to right
li[-n:] + li[:-n]
li[-1:] + li[:-1]
[5, 1, 2, 3, 4]
''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))
# abcdeffgvcg
list(list(x) for x in zip(*old_list))
# old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]
list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))
# [2, 4, 6]
a, *b, c = [1, 2, 3, 4, 5]
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5

I have provided the link to my Github repo below which has all these one-liners. Feel free to contribute more amazing one-liners. Happy coding!

Python Developer | Django Developer | Python Enthusiast