Professional Documents
Culture Documents
Python
Python
IF
IF
IF
WHILE
FOR
TERNARY
LIST
LIST
LIST Add as is
LIST Unpack and add
LIST update
LIST iterate
LIST iterate
LIST iterate
LIST iterate
LIST remove
LIST Index
LIST sort
LIST flatten
LIST to string
LIST to string
LIST count
LIST reverse
LIST reverse
LIST reverse
LIST duplicates
LIST duplicates
LIST insert
LIST remove
LIST remove
LIST remove
LIST remove a range
LIST sort list of classes
LIST copy
LIST sort two keys
LIST sort
STRING search
STRING search any
STRING search all
STRING iterate
STRING replace
STRING remove
DICT create
DICT Add
DICT Add
DICT delete
DICT delete
DICT delete
DICT sort
FUNCT FILTER()
FUNCT FILTER()
TUPLE UNPACK
FUNCTION _MAIN_
FUNCTION ITERate
FUNCTION FILTER()
FUNCTION ZIP()
DICT CReate from LIST
FUNCTION Enumerate
FUNCTION EVAL
FUNCTION RANGE
FUNCTION SUM
FUNCTION MAP
FUNCTION FILTER()
FUNCTION REDUCE()
FUNCTION ZIP()
DICT create from ZIP
FUNCTION Recursive
FUNCTION iterative
NOTES Iterator and Iterable
NOTES Iterator
FUNCTION LAMBDA
FUNCTION Global
DATETIME add days
LIST Average
LIST Unique
LIST Init 2D
MAP
DICT sort
LIST to dict
Syntax
"if x > 10 and x < 20 and x != 15:
print('x iselse
print('The greater than 10')"
block')
BREAK
while CONTINUE
x <= 100 PASS
and count < 10:
if x % 2 == 0:
for i in range(1, 11):
result = 'High' if x > 10 else 'Low'
listOfStrings1 = ['Hi'] * 20
listOfStrings2 = ['Hi' for i in range(20)]
wordList.append(["one", "use", "data"])
wordList.extend(["one", "use", "data"])
list_of_numbers[0:3] = [10, 10, 10]
for word in wordList:
print(wordList[i])
i += 1
print(wordList[i])
i += 1
[print(i) for i in wordList]
a = [5, 7, 9]
b = ['Alice', 'Bob', 'Ann']
zipped = list(zip(a, b))
# [(5, 'Alice'), (7, 'Bob'), (9, 'Ann')]
zipped.sort(key=lambda
lst = [99, 3, 8, 1, 12]x: x[1])
lst_2 = lst[:1] + sorted(lst[1:])
Triple quotes
y.strip() for multiline
- remove strings '''Yes''' or """Yes"""
white space
if "sample" in mainStr:
if "Hello" not in mainStr:
if "SAMple".lower() in mainStr.lower():
result = any(([True if subStr in mainStr else False for subStr in listOfs
result = all(([True if subStr in mainStr else False for subStr in listOfs
for elem in sampleStr[ : :-1]:
sample_string = "This is a sample string"
char_to_replace = {'s': 'X',
'a': 'Y',
'i': 'Z'}
# Iterate over all key-value pairs in dictionary
for key, value in char_to_replace.items():
# Replace key character with value character in string
sample_string = sample_string.replace(key, value)
OR
sample_string = sample_string.translate(str.maketrans(char_to_replace))
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
return True if letter in vowels else False
filtered_vowels = filter(filter_vowels, letters)
aquarium_tanks = [11, False, 18, 21, "", 12, 34, 0, [], {}]
list(filter(None, aquarium_tanks))
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def iterative_factorial(n):
result = 1
for i in range(2,n+1):
result *= i
return result
Every iterator is also an iterable, but not every iterable is an iterator
An iterator can be created from an iterable by using the function 'iter'.
needs either a method '__iter__', which returns an iterator, or a '__geti
def iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
for element in [34, [4, 5], (4, 5), {"a":4}, "dfsdf", 4.5]:
print(element, "iterable: ", iterable(element))
Lazy Evaluation
converter = lambda x : x*2 if x < 10 else (x*3 if x < 20 else x)
def mySum(*args):
return sum(args)
def fun(**kwargs):
for key in kwargs:
print("%s = %s" % (key, kwargs[key]))
# Driver code
fun(name="geeks", ID="101", language="Python")
first, *_, last = [1, 2, 3, 5, 7]
values = (1, 2, 3, 4, 5)
def add_numbers(*args):
total = 0
for num in args:
total += num
print(total)
return total
add_numbers(*values)
print(f'Number\t\tSquare\t\t\tCube')
for x in range(1, 11):
x = float(x)
print(f'{x:5.2f}\t\t{x*x:6.2f}\t\t{x*x*x:8.2f}')
print(f'{"apple" : <30}')
print(f'{"apple" : ^30}')
print(f'{number
items[:] = [] = }')
items.clear()
duplicated_list = [1,1,2,1,3,4,1,2,3,4]
deduplicated_list = np.unique(np.array(duplicated_list)).tolist()
abs_array = np.abs(sample_array)
duplicated_list = [1,1,2,1,3,4,1,2,3,4]
df['Distance Absolute'] = df['Distance'].abs()
deduplicated_list = pd.Series(duplicated_list).unique().tolist()
list_of_tuples = list(sample_dict.items())
list_of_tuples = [(key, value) for key, value in sample_dict.items()]
list_of_tuples = list(zip(keys, values))
list_of_tuples
intersection == [item
list()for item in list1 if item in list2]
random.shuffle(a_list)
for key in sample_dict:
intersection
shuffled = list(set(list1).intersection(set(list2)))
= random.sample(a_list,
list_of_tuples.append((key, len(a_list))
sample_dict.get('key')))
intersection = list(set(list1) & set(list2))
intersection = list(np.intersect1d(list1, list2))
subtracted = [element1 - element2 for (element1, element2) in zip(l
array = np.array(list_of_lists)
transposed_array = array.T
transposed_list_of_lists = transposed_array.tolist()
from itertools import combinations
for i in range(len(list_of_lists[0])):
sample_list = ['a', 'b', 'c']
row = list()
list_combinations = list()
for sublist in list_of_lists:
for n inrow.append(sublist[i])
range(len(sample_list) + 1):
transposed.append(row)
flat_list = [item for sublist
list_combinations in list_of_lists for item in
+= list(combinations(sample_list, n))sublist]
new_ages = {key:value for (key, value) in ages.items() if value > 2
transposed
oddeven = [[row[i] for
= {key:('odd' ifrow in list_of_lists]
value % 2 == 1 elsefor i in range(len(list_o
'even') for (key, valu
from
for n itertools
in import chain
range(len(sample_list)
print(transposed) + 1):
names
new_list = ['Harry',
==[i 'Hermione', 'Ron',
101) 'Neville', 'Luna']
flat_list =for i in+=range(1,
list(chain(*list_of_lists))
list_combinations
chunked_list if ifor
% 2i==in0range(0,
if i % 5len(our_
list(combinations_with_replacement(sample_
[our_list[i:i+chunk_size] == 0]
index
flat_list = {k:v= [ifor for (k,
j v)
in in enumerate(names)}
nested_list for i in j]
smalldict
common_items = [i for i in list1 if ('a',
= {k: bigdict[k] for k in 'b', 'c')}
i in list2]
ages = {key:ages[key] for key in ages.keys() - {'marcus', 'nik'}}
import
joined pprint
dictionary = ' = {value:key for (key:value)
'.join(our_list) -- Error if in dictionary}
different data types
import
sample_dictstring = {'name': 'Nik', 'age': 31, 'gender': 'male',
alphabet
'books':
sorted_dict = list(string.ascii_lowercase)
['Harry Potter',for
= {key:value 'Lord
key, ofvalue
the Rings']}
in sorted(sales.items(), ke
new_word = word
pprint.pprint(sample_dict) + str(integer)
new_word
for i in =
max_keys = f'{word}{integer}'
range(97,
[key for123): key, value in ages.items() if value == max(ages
str(number).zfill(7)
new_word = '{}{}'.format(word, integer)
alphabet.append(chr(i))
a_string.rjust(10, ' ')
message = ( ... f"Hello, my name is {name}. "
f"I
type(x)can calculate
is not intpi to two places: {pi:4.3}. "
f"But I would rather be eating {food}.
isinstance([1,2,3,4], list)
t = 1
def increment():
global t # now t inside the function is same as t outside the funct
t = t + 1
print(t) # Displays 2
increment()
from datetime import datetime, timedelta
def filter_unique(lst):
return [item for item, count in Counter(lst).items() if count > 1]
def has_duplicates(lst):
return len(lst) != len(set(lst))
def initialize_2d_list(w, h, val = None):
return [[val for x in range(w)] for y in range(h)]
def map_dictionary(itr, fn):
return dict(zip(itr, map(fn, itr)))
map_dictionary([1, 2, 3], lambda x: x * x) # { 1: 1, 2: 4, 3: 9 }
def most_frequent(lst):
return max(set(lst), key = lst.count)
Append is faster
LOGGING
loGGING
Syntax
finally:
print('in finally block')
finally:
EmailOrderStatusToUser(id) # Either ways send order email to user
# handle all other exceptions
pass
print('Unexpected Error!')
exit()
raise # Just raise
# raise UserDoesNotExist # Don't do this or you'll lose the stack trace
print 'FILE:'
print body
for filename in logfiles:
print filename
Type How to
Array Create
Array Reshape
Array Dimension
Array Slicing
Array Boolean Indexin
Array multiply
Array Flatten
Array Transpose
Array Concatenate
Array shape
Array append
Array unique
Array String
Array Round
Array Arith
Array Mean
Array Average
Array max,min
Array Where
Array Extract
Array view
Array Random
Array Replace
Array Select
Array Remove Nan
y
x == x[[0,1,2],
np.ones(5) [0,1,0]] -- [1 4 5]
x
a == np.ones([2,2], dtype=int)
np.array([[1,2,3],[4,5,6]])
x
a =
= np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
np.asarray(lst)
b = a.reshape(3,2)
rows = np.array([[0,0],[3,3]])
x = np.arange(5, dtype=float)
cols = np.array([[0,2],[0,2]])
x = np.arange(10,20,2)
a=np.array([[1,2,3],[4,5,6]])
Syntax
y
x == x[rows,cols]
np.linspace(10,20,5)
a.shape=(3,2)
https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md
-- Corner elements
np.linspace(10,20,
x = np.array([[ 5, endpoint=False)
0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
x[x>5]
a = np.arange(24)
x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]])
b = a.reshape(2,4,3)
z
a == x[1:4,1:3]
np.array([np.nan, 1,2,np.nan,3,4,5])
ndarray.ndim
y = x[1:4,[1,2]] -- Indexing
a[~np.isnan(a)]
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c
a == np.arange(8).reshape(2,4)
a*b
a=np.array([[1,2],[3,4]])
np.char.center(arr, width,fillchar)
a.flatten()
a ==np.arange(12).reshape(3,4)
b np.array([[5,6],[7,8]])
np.char.center('hello', 20,fillchar='*')
np.transpose(a) or a.T
np.concatenate((a,b),axis=1)
a = np.array([[1,2,3],[4,5,6]])
np.concatenate((a,b),axis=0)
np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep=',')
b ==np.resize(a,
a (3,2))
np.array([[1,2,3],[4,5,6]])
np.char.join(':','dmy')
b.shape
np.append(a, [[7,8,9]],axis=0)
u,indices=np.unique(a,
np.char.replace ('He isreturn_index=True)
a good boy', 'is', 'was')
np.append(a, [[7,8,9]],axis=1)
u,indices=np.unique(a,return_counts=True)
np.around(a, decimals=1)
np.floor(a)
np.add(a,b)
np.ceil(a)
np.multiply(a,b)
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
np.divide(a,b)
np.mean(a)
np.subtract(a,b)
np.mean(a, axis=0)
np.average(a)
maxindex= np.argmax(a)
np.mean(a, axis=1) 4],weights=[4,3,2,1], returned=True)
np.average([1,2,3,
a.flatten()[maxindex]
x = np.arange(9.).reshape(3, 3)
np.average(a, axis=1, weights=wt)
y=np.where(x>3)
maxindex=np.argmax(a,
x = random.rand() -- Float axis=1)
from 0 to 1
x=random.randint(100, size=(5))
condition = np.mod(x,2)==0
x = random.randint(100, size=(3, 5))
col
b = = 'consumption_energy'
np.extract(condition,
a.view() -- x) Orig will not be changed
x = random.choice([3, 5, 7, 9])
conditions
Slice creates a view 5, 7, 9],(df2[col]
= [df2[col] >= 400, < 400) & (df2[col] > 200), df2[col] <= 200]
x
b =
= random.choice([3,
np.where(a > 0,'medium',
a, 0) size=(3, 5))
choices = ["high", 'low']
np.where((a > 2) & (a < 6) | (a == 7), -1, 100)
df2["energy_class"] = np.select(conditions, choices,
default = np.nan)
x[~np.isnan(x)]
~np.isnan(x).any(axis=1)
th_solutions.md
#int8, int16, int32, int64 can be replaced by equivalent string 'i1',
'i2','i4', etc
roupby('Courses',sort=False).sum()sortedDF=groupedDF.sort_values('Courses', ascending=False)df.groupby(
ess', 'Kurtosis']
.com/datagy/pivot_table_pandas/raw/master/sample_pivot.xlsx', parse_dates=['Date'])pd.read_csv("https:/
y,value pairsprint(df.groupby('region').groups.keys())print(df.groupby('region').get_group('South')) -
sv")pd.read_json("https://data.cityofchicago.org/resource/tq3e-t5yq.json")"https://raw.githubuserconten
https://www.studytonight.com/python/property-in-python