Python Flashcards
Find length of list
length = len(list)
For loop for list
for element in list:
If, elif, else
if condition1:
elif condition2:
else:
If, elif, else
if condition1:
elif condition2:
else:
Print value
print(value)
Print floating point number with precision
print(f’{value:.6f}’)
Initiate variable
variable = 0
Increase a count
count += 1
Decrease a count
count -= 1
Initialise a variable to positive infinity
variable = float(‘inf’)
Initialise a variable to negative infinity
variable = -float(‘inf’)
Print multiple values in one line in Python
print(f’{value1} {value2}’)
Replace a substring in a string in python
new_string = old_string.replace(‘old_substring’, ‘new_substring’)
Check if substring in string
if ‘substring’ in string:
How to get a substring of first n numbers of characters
substring = string[:2]
Get substring of characters after first 2
substring = string[2:]
Convert string to int
number = int(string)
Convert number to string
str(number)
Replace first occurrence of a substring in Python
new_string = old_string.replace(‘old_substring’, ‘new_substring’, 1)
How to iterate from 1 to n inclusive in a for loop using range
for i in range(1, n+1)
Iterate from 0 to n exclusive in a for loop using range
for i in range(n):
Iterate from starting value to an ending value with a specific step in a for loop
for i in range(start, stop, end):
How to check if a number is divisible by another number
number % division == 0
Iterate backwards from n to 1 inclusive using range
for i in range(n, 0, -1):
Sort list in place
list.sort()
Find floor of a number
import math
math.floor(number)
Find ceiling of a number
import math
math.ceil(number)
Create an empty dictionary
dictionary = {}
Check if key exists in dictionary
if key in dictionary:
Delete key value pair
del dictionary[key]
Add key value pair
dictionary[key] = value
Get list of all keys in a dictionary
keys = list(dictionary.keys())
Calculate the trace of diagonal elements
import numpy as np
np.trace(matrix)
Transpose a matrix and find trace
import numpy as np
np.trace(matrix.T)
Iterate through the rows of a square matrix
for i in range(len(matrix)):
Access elements on the primary diagonal of a square matrix
matrix[i][i]
Access element on the secondary diagonal of a square matrix
matrix[len(matrix) - 1 - i][i]
Find absolute value of a number
abs(number)