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]
from collections import Counter
s1 = 'below'
s2 = 'elbow'
print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')
decimal = int('1010', 2)
print(decimal) #10
bin(24)
hex(24)
oct(24)
dict(name='allwin', age=23)
"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')
li = [1, 2, 3, 4, 5]
del li[0:3]
# [4, 5]
exec('print("hello world!")')
# hello world!
lambda x: x if x<=1 else fib(x-1) + fib(x-2)
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
n = 5
print('\n'.join('* ' * i for i in range(1, n + 1)))
*
* *
* * *
* * * *
* * * * *
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))
a,b = b,a
[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]
python3 -m http.server 8000
python2 -m SimpleHTTPServer
import math; fact_5 = math.factorial(5)
print(5//2)
# 2
new_li = [number for number in [1, 2, 3, 4] if number % 2 == 0]
# [2, 4]
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
# 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(0,5) }
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'))
d = {320: 1, 321: 0, 322: 3}
max_value_key = max(d, key=d.get)
# 322
list1.extend(list2)
# contents of list 2 will be added to the list1
or
[1, 2] + [3, 4]
# [1, 2, 3, 4]
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
d = {320: 1, 321: 0, 322: 3}
min_value_key = min(d, key=d.get)
# 321
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
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)]
numbers = [[num] for num in range(10)]
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
obj_1 = type('obj_1', (object,), {'property': 'value'})()
print(int('30', 8))
# 24
import itertools; print(list(itertools.repeat(10,5)))
# [10, 10, 10, 10, 10] will be printed
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
quotient, remainder = divmod(4,5)
import this
list(set([4, 4, 5, 5, 6]))
sorted([5, 2, 9, 1])
sorted([5, 2, 9, 1], reverse=True)
import string; print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
import string; print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
import string; print(string.digits)
# 0123456789
digits = [int(digit) for digit in str(12345)]
print(int('da9', 16))
# 3497
import math; math.hypot(8, 6)
import time; print(time.ctime())
# Thu Aug 13 20:16:23 2020
list(map(int, ['1', '2', '3']))
# [1, 2, 3]
" ".join(["hello", "world"])
# "hello world"
dict(zip([1,2,3,4], ['a','b','c','d']))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
list1 = [1, 2, 4, 5]
list2 = [6, 8, 4, 2]
print(set(list1) & set(list2))
print(set(list1).intersection(set(list2)))
# {2, 4}
list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))
# [2, 4, 6]
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)]
$ python -m cProfile foo.py
from itertools import permutations
print([''.join(perm) for perm in permutations('abc')])
# ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
import itertools
prefix_sum = itertools.accumulate([1, 2, 3, 4, 5])
print(list(prefix_sum))
# [1, 3, 6, 10, 15]
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]
''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))
# abcdeffgvcg
string = "He is a good boy"
string.replace('good', 'bad')
# returns 'he is a bad boy'
# replace everythin in one go
import re
re.sub(r'[.+()@]', '', 'A(ll+wi)@n.')
# 'Allwin'
# replace-multiple-spaces
s = 'string with multiple spaces and \n\n new lines'
' '.join(s.split()) # 'string with multiple spaces and new lines'
numbers[::-1]
# 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]
# 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}
# {'one': 1, 'four': 4, 'eight': 8}
{key:d[key] for key in sorted(d.keys())}
# {'eight': 8, 'four': 4, 'one': 1}
'sent' in 'sentence'
# returns True
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]]
a, *b, c = [1, 2, 3, 4, 5]
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5
Source: https://github.com
#python