This github repo is a collection of amazing python one liners which I regularly use which saved me a lot of time. Feel free to add more to the list.
- Sort a dictionary based on multiple conditions
- Thousand Separator
- Multiply all elements of a list
- Flatten a List
- Remove duplicate elements from a list
- Get quotient and remainder
- Most frequent element of a List
- Convert string to upper case
- Converting string to byte
- Transpose a Matrix
- Element wise addition of 2 lists
- Convert ASCII value to Character and vice versa
- Print all combinations of elements in a List
- Input space separated integers in a list
- Nested for loops via List comprehension
- Find All Indices of an Element in a List
- Convert number of any base to decimal
d={'IN':2, 'GE':2, 'AK':3, 'BEG':1}
n_l=sorted(d.items(), key=lambda x: (x[1], len(x[0]),x[0]))
new_d={k:v for k,v in n_l}
# new_d = {'BEG': 1, 'GE': 2, 'IN': 2, 'AK': 3}
n=10000000
new_number=f'{n:,}'
# new_number = 10,000,000
from numpy import prod
from functools import reduce
l=[2,3,4,4,5,6]
v1=prod(1) # 2880
v2=reduce((lambda x, y: x * y), l) #2880
l = [[7,6], [4, 6], [8, 10]]
flattened = [i for j in l for i in j]
# flattened = [7, 6, 4, 6, 8, 10]
l = [4,4,5,5,6]
new_l=list(set(l))
# new_1 = [4,5,6]
quotient, remainder = divmod(10,5)
# quotient, remainder = 2,0
from collections import Counter
l = [1,1,3,4,1,5,6,7,7,2,9]
freq_ele=Counter(l).most_common()[0][0]
# freq_ele = 1
"hi my name is Allwin".upper()
# 'HI MY NAME IS ALLWIN'
s="My name is fox and fox is an animal"
s.encode()
# b'My name is fox and fox is an animal'
matrix = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]
l=list(list(x) for x in zip(*matrix))
# l = [[1, 3, 5], [2, 4, 6], [3, 6, 7]]
first = [1,2,3,4,5]
second = [6,7,8,9,10]
final=[x + y for x, y in zip(first, second)]
# final = [7, 9, 11, 13, 15]
ord('a') # 97
chr(97) # a
chr(ord('a') + 3) #d
from itertools import combinations, combinations_with_replacement
nums = [1,2,3,4]
list(combinations(nums, 2))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
list(combinations_with_replacement(nums, 2))
# [(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]
list(combinations (nums, 3))
# [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
l = list(map(int, input().split()))
l = [line.strip() for line in open('abc.txt', 'r')]
l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c']
l = [(x, y) for x in l1 for y in l2]
# [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), (4, 'a'), (4, 'b'), (4, 'c')]
lst = ['a', 'v', 'a', 'c', 'z']
indices = [i for i in range(len(lst)) if lst[i]=='a']
# [0, 2]
int('30', 8) # 24
int('1011', 2) # 11
int('1A', 16) # 26