Python one-liners

This blog post contains some of the python one-liners which I have gathered from various sources. The link to the repository is given below. If you are interested you can also add your own one-liners if I have missed any.

https://github.com/Allwin12/python-one-liners

anagram

from collections import Counter

s1 = 'below'
s2 = 'elbow'

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

binary to decimal

decimal = int('1010', 2)
print(decimal) #10

convert string to lower case

"Hi my name is Allwin".lower()
# 'hi my name is allwin'
"Hi my name is Allwin".casefold()
# 'hi my name is allwin'

convert string to upper case

"hi my name is Allwin".upper()
# 'HI MY NAME IS ALLWIN'

convert string to bytes

"convert string to bytes using encode method".encode()
# b'convert string to bytes using encode method'

copy files

import shutil; shutil.copyfile('source.txt', 'dest.txt')

quick sort

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 of n consecutive numbers

sum(range(0, n+1)

swap two values

a,b = b,a

fibonacci series

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

flat list out of list of lists

[item for sublist in main_list for item in sublist]

starting a http server

python3 -m http.server 8000

reverse a list

numbers[::-1]

factorial of a number

import math; fact_5 = math.factorial(5)

floor division result

print(5//2)
# 2

for and if

new_li = [number for number in [1, 2, 3, 4] if number % 2 == 0]
# [2, 4]

longest string in a list

# words = ['This', 'is', 'a', 'list', 'of', 'words']
max(words, key=len)
# 'words'

list comprehension

li = [num for num in range(0,100)]
# this will create a list of numbers from 0 to 99

set comprehension

num_set = { num for num in range(0,100)}
# this will create a set of numbers from 0 to 99

dictionary comprehension

dict_numbers = {x:x*x for x in range(0,5) }

if else

print("even") if 4%2==0 else print("odd")

infinite while loop

while 1:0

check data type

isinstance(2, int)
isinstance("allwin", str)
isinstance([3,4,1997], list)

while loop

a=5
while a > 0: a = a - 1; print(a)

write to a file using print

print("Hello, World!", file=open('file.txt', 'w'))

count occurence of a character in a string

print("umbrella".count('l'))

merge two lists

list1.extend(list2)
# contents of list 2 will be added to the list1

merge two dictionaries

dict1.update(dict2)
# contents of dictionary 2 will be added to the dictionary 1 

merge two sets

set1.update(set2)
# contents of set2 will be copied to the set1

get timestamp

import time; print(time.time())

most frequent element in a list

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]
most_frequent_element = max(set(test_list), key=test_list.count)
# 4
from collections import Counter

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]
print(list(Counter(numbers).most_common()))
# [(4, 4), (5, 3), (9, 2)]

nested list comprehension

numbers = [[num] for num in range(10)]
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]

octal to decimal

print(int('30', 8)) 
# 24

repeat values in a list for n time

import itertools; print(list(itertools.repeat(10,5)))
# [10, 10, 10, 10, 10] will be printed

generate a random number of n digits

from random import randint; print(''.join(["{}".format(randint(0, 9)) for num in range(0, n)]))
# This will print 1038496714 given the value of n=10

convert key value pair to dictionary

dict(name='allwin', age=23)

get quotient and remainder

quotient, remainder = divmod(4,5)

python zen

import this

remove duplicate elements from a list

list(set([4, 4, 5, 5, 6]))

sort list in ascending order

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

sort list in descending order

sorted([5, 2, 9, 1], reverse=True)

get a string of small case alphabets

import string; print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz

get a string of upper case alphabets

import string; print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ

get a string of digits from 0 to 9

import string; print(string.digits)
# 0123456789

get individual digits from a number

digits = [int(digit) for digit in str(12345)]

hexadecimal to decimal

print(int('da9', 16))
# 3497 

hypotenuse

import math; math.hypot(8, 6)

human readable datetime

import time; print(time.ctime())
# Thu Aug 13 20:16:23 2020

convert decimal to binary

bin(24)

convert decimal to octal

oct(24)

convert decimal to hexadecimal

hex(24)

convert a list of strings to integers

list(map(int, ['1', '2', '3']))
# [1, 2, 3]

combine strings from a list

" ".join(["hello", "world"])
# "hello world"

combine two lists to dictionary

dict(zip([1,2,3,4], ['a','b','c','d']))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

common element between two lists

list1 = [1, 2, 4, 5]
list2 = [6, 8, 4, 2]

print(set(list1) & set(list2))
print(set(list1).intersection(set(list2)))
# {2, 4}

get even numbers from a list

list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))
# [2, 4, 6]

input a list of tuples

list(tuple(map(int, input().split())) for r in range(int(input('enter the no of rows:'))))
# enter the no of rows:
# 3
# 1 2
# 3 4
# 5 6
# [(1, 2), (3, 4), (5, 6)]

transpose matrix

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

remove numbers from string

''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))
# abcdeffgvcg

replace words in a sentence

string = "He is a good boy"
string.replace('good', 'bad')
# returns 'he is a bad boy'

rotate a list

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

sort dictionary with values

# 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}

sort dictionary with key

# {'one': 1, 'four': 4, 'eight': 8}
{key:d[key] for key in sorted(d.keys())}
# {'eight': 8, 'four': 4, 'one': 1}

substring in a string

'sent' in 'sentence'
# returns True

unpacking elements

a, *b, c = [1, 2, 3, 4, 5]
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5

Leave a Reply

Your email address will not be published. Required fields are marked *