Creating a comprehensive Python cheat sheet is a bit extensive, but I can provide you with a condensed version covering various aspects of Python.
Overview
This cheat sheet covers various aspects of Python programming, from basics to advanced topics. Feel free to expand on each section or include more topics based on your specific needs or interests. Let’s dive into basics of Python.
Variables
Variable Assignment:
>>> x=5
>>> x
5
Calculations With Variables:
>>> x+2 #Sum of two variables
7
>>> x-2 #Subtraction of two variables
3
>>> x*2 #Multiplication of two variables
10
>>> x**2 #Exponentiation of a variable
25
>>> x%2 #Remainder of a variable
1
>>> x/float(2) #Division of a variable
2.5
Types and Type Conversion:
str() '5', '3.45', 'True'
int() 5, 3, 1
float() 5.0, 1.0
bool() True, True, True
Variables to strings
Variables to integers
Variables to floats
Variables to booleans
Asking For Help
In Python, the help()
function is used to get information about modules, classes, functions, methods, and keywords.
>>> help(str)
Strings
A string is a sequence of characters enclosed within either single quotes ('
) or double quotes ("
). Strings are immutable.
>>> my_string = 'thisStringIsAwesome'
>>> my_string
'thisStringIsAwesome'
String Operations:
>>> my_string * 2
'thisStringIsAwesomethisStringIsAwesome'
>>> my_string + 'Innit'
'thisStringIsAwesomeInnit'
>>> 'm' in my_string
True
>>> my_string[3]
>>> my_string[4:9]
String Methods:
>>> my_string.upper() #String to uppercase
>>> my_string.lower() #String to lowercase
>>> my_string.count('w') #Count String elements
>>> my_string.replace('e', 'i') #Replace String elements
>>> my_string.strip() #Strip whitespaces
Lists
List items are ordered, changeable, and allow duplicate values.
>>> a = 'is'
>>> b = 'nice'
>>> my_list = ['my', 'list', a, b]
>>> my_list2 = [[4,5,6,7], [3,4,5,6]]
Selecting List Elements:
Subset
>>> my_list[1] #Select item at index 1
>>> my_list[-3] #Select 3rd last item
Slice
>>> my_list[1:3] #Select items at index 1 and 2
>>> my_list[1:] #Select items after index 0
>>> my_list[:3] #Select items before index 3
>>> my_list[:] #Copy my_list
Subset Lists of Lists
>>> my_list2[1][0] #my_list[list][itemOfList]
>>> my_list2[1][:2]
List Operations:
>>> my_list + my_list
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
>>> my_list * 2
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
>>> my_list2 > 4
True
List Methods:
>>> my_list.index(a) #Get the index of an item
>>> my_list.count(a) #Count an item
>>> my_list.append('!') #Append an item at a time
>>> my_list.remove('!') #Remove an item
>>> del(my_list[0:1]) #Remove an item
>>> my_list.reverse() #Reverse the list
>>> my_list.extend('!') #Append an item
>>> my_list.pop(-1) #Remove an item
>>> my_list.insert(0,'!') #Insert an item
>>> my_list.sort() #Sort the list
NumPy Arrays
NumPy (Numerical Python) is a popular library in Python used for numerical computing.
>>> my_list = [1, 2, 3, 4]
>>> my_array = np.array(my_list)
>>> my_2darray = np.array([[1,2,3],[4,5,6]])
NumPy Array Operations:
>>> my_array.shape #Get the dimensions of the array
>>> np.append(other_array) #Append items to an array
>>> np.insert(my_array, 1, 5) #Insert items in an array
>>> np.delete(my_array,[1]) #Delete items in an array
>>> np.mean(my_array) #Mean of the array
>>> np.median(my_array) #Median of the array
>>> np.corrcoef([], []) #Correlation coefficient
>>> np.std(my_array) #Standard deviation
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
['apple', 'banana', 'mango']
Python Functions and Arguments
A function is a block of code which only runs when it is called.
Normal Function Definition:
def my_function(x):
print(x)
my_function(5)
Arbitrary Arguments, *args:
def my_function(*args):
print("The youngest child is " + args[2])
my_function("Akki", "Chakki", "Makki")
Arbitrary Keyword Arguments, **kwargs:
def my_function(**kwargs):
print("His last name is " + kwargs["lname"])
my_function(fname = "Elon", lname = "Musk")
Decorator
In Python, a decorator is a design pattern that allows you to modify the functionality of a function by wrapping it in another function.
Calling ordinary function normally:
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
let’s call it using the decorator function:
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
decorated_func = make_pretty(ordinary)
decorated_func()
@ Symbol With Decorator:
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
@make_pretty
def ordinary():
print("I am ordinary")
ordinary()
Zip Function
The zip() function creates an iterator that will aggregate elements from two or more iterables.
Passing No Arguments:
zipped = zip()
zipped
list(zipped)
Passing One Argument:
a = [1, 2, 3]
zipped = zip(a)
list(zipped)
Passing n Arguments:
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
flotty = [1.1, 2.2, 3.3]
zipped = zip(numbers, letters, flotty)
zipped
list(zipped)
Calculating in Pairs Example:
total_sales = [52000.00, 51000.00, 48000.00]
prod_cost = [46800.00, 45900.00, 43200.00]
for sales, costs in zip(total_sales, prod_cost):
profit = sales - costs
print(f'Total profit: {profit}')
Lambda
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
x = lambda a : a + 20
print(x(5))
Lambda & Apply:
The apply() function calls the lambda function and applies it to every row or column of the dataframe and returns a modified copy of the dataframe.
import pandas as pd
df=pd.DataFrame({
'id':[1,2,3,4,5],
'name':['Jeremy','Frank','Janet','Ryan','Mary'],
'age':[20,25,15,10,30],
'income':[4000,7000,200,0,10000]
})
print(df)
df['age']=df.apply(lambda x: x['age']+3,axis=1)
Lambda With Filter Function:
Let’s see how many of these people are above the age of 18.
list(filter(lambda x: x>18, df['age']))
Lambda With Map Function:
Let’s increase the salary of each person by 20% in our Pandas dataframe.
df['income']=list(map(lambda x: int(x+x*0.2),df['income']))
Lambda With Reduce Function:
Let’s see the total income of all persons.
import functools
functools.reduce(lambda a,b: a+b, df['income'])