Skip to content

ETretyakov/python-one-liners

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

This github repo is a collection of amazing python one liners.

A

B

C

D

E

F

G

H

I

L

M

N

O

P

Q

R

S

T

U

W

alternate elements

Elements from even index

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(li[0::2])
# [1, 3, 5, 7, 9]

Elements from odd index

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(li[1::2])
# [2, 4, 6, 8, 10]

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 decimal to binary

bin(24)

convert decimal to hexadecimal

hex(24)

convert decimal to octal

oct(24)

convert key value pair to dictionary

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

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')

deleting multiple elements from a list

li = [1, 2, 3, 4, 5]
del li[0:3] 
# [4, 5]

execute strings

exec('print("hello world!")')
# hello world!

fibonacci series

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

fizzbuzz

n = 20
print('\n'.join('Fizz' * (i%3==0) + 'Buzz' * (i%5==0) or str(i) for i in range(1, n)))

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19

half pyramid

n = 5
print('\n'.join('* ' * i for i in range(1, n + 1)))

*
* *
* * *
* * * *
* * * * *

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

flatten list

[item for sublist in main_list for item in sublist]

Using itertools

import itertools
print(list(itertools.chain.from_iterable(a_list)))
[1, 2, 3, 4, 5, 6]

starting a http server

python3 -m http.server 8000
python2 -m SimpleHTTPServer

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]

lambda function with if else

list(map(lambda x: x if x%2==0 else x+1, [1, 2, 3, 4]))
# [2, 2, 4, 4]
# converts only odd numbers to even numbers by adding 1 to it

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

or

[1, 2] + [3, 4]
# [1, 2, 3, 4]

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

object creation

obj_1 = type('obj_1', (object,), {'property': 'value'})()

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

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

performance profiling

$ python -m cProfile foo.py

permutation

from itertools import permutations
print([''.join(perm) for perm in permutations('abc')])

# ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

prime numbers in a range

primes = list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 100)))
print(primes)
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

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'

replace with regular expression

# replace everythin in one go

import re
re.sub(r'[.+()@]', '', 'A(ll+wi)@n.')
# 'Allwin'

replace multiple spaces

# replace-multiple-spaces
s = 'string with  multiple    spaces and \n\n new lines'
' '.join(s.split()) # 'string with multiple spaces and new lines'

reverse a list

numbers[::-1]

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

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

unpacking elements

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

About

This repository contains python one-liners obtained from various sources.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published