Cheat Sheets #3: Python Essentials, Object Oriented, Data Structures, Complexities, Flask

Speedster Saurabh
10 min readJun 1, 2020

Learning any new concept is difficult for newbies. Are you finding difficult in remembering all the syntax that you need to work with Python for Data Science? Guys, don’t worry if you are a beginner and have no idea about how Python works, this Python cheat sheet will give you a quick reference of the basics that you must know to get started. I am creating this series with cheat sheets which I collected from different sources.

Over the past few months, totally redesigned the cheat sheets. The goal was to make them easy to read and beautiful so you will want to look at them, print them and share them.

Do read this and contribute cheat sheets if you have any. If you like this post, give it a ❤️. Here we go:

1. Python Basics Cheat Sheet

Basic:

Python is a high-level dynamic programming language which is very easy to learn. It comes with powerful typing and the codes are written in very ‘natural’ style, thats the reason, it is easy to read and understand. Python programming language can run on any platform, from Windows to Linux to Macintosh, Solaris etc.

Basic rules to write Python syntax:

Rule #1: Python is white-space dependent; code blocks are indented using spaces.
Rule #2: Python language is case sensitive. It matters for variables, functions and any keyword in general.

Data Types

In Python, every value has a datatype. in Python programming, everything is an object, data types are classes and variables are instance that means object of these classes.
There are various data types in Python. Some of the important types are listed below.

  • Numbers: a=2(Integer), b=2.0(Float), c=1+2j(Complex)
  • List: a=[1,2,3,’Word’]
  • Tuple: a= (1,2,4)
  • String: a=“New String”
  • Sets: a= {2,3,4,5}
  • Dictionary: x= {‘a’: [1,2],‘b’: [4,6]

Operators

In python, Operators are only the constructs which can manipulate the value of operands. For example, in the expression 5 + 10 = 15. Here, 5 and 10 are operands and + is operator.

Numeric Operator (Say, a holds 5, b holds 10)

  • a + b = 15
  • a — b = -5
  • a * b = 50
  • b/a = 2
  • b % a = 0
  • a**b =510
  • 0//2.0 = 3.0, -11//3 = -4

Comparison Operator

  • (a == b): not true
  • (a!= b): true
  • (a > b): not true.
  • (a > b): not true
  • (a >= b): not true
  • (a <= b) is true

Boolean Operator

  • a and b
  • a or b
  • not a

Operations

Python provides some of the built-in operations on various data types.

List Operations

  • List=[]:Defines an empty list
  • list[i]=a: Stores a at the ith position
  • list[i]: Retrieves the character at the ith position
  • list[i:j]: Retrieves characters in the range i to j
  • append(val): Adds item at the end
  • pop([i]): Removes and returns item at index i

String Operations

  • String[i]: Retrieves the character at the ith position
  • String[i:j]: Retrieves characters in the rangei to j

Dictionary Operations

  • dict={} : Defines an empty dictionary
  • dict[i]=a: stores “a” to the key “i”
  • dict[i]: Retrieves the item with the key “i”
  • key: Gives all the key items
  • values: Gives all the values

Flow Control Method:

Python programming language provides various looping and control statement that allow for more complicated execution paths.A loop statement allows us to execute a statement or group of statements multiple times.

if-else (Conditional Statement):

if price>=700: print(“Buy.”) else: print(“Don’t buy.”)

For loop (Iterative Loop Statement):

a=“New Text” count=0 for i in a: if i==‘e’: count=count+1 print(count)

While loop (Conditional Loop Statement):

a=0 i=1 while i<10: a=a*2 i=i+1 print(a)

Loop Control: Break, Pass and continue

Functions

A function is a block of code which only runs when it is called. We can pass data (parameters) into a function and after executing a function, it will return data as a result.

def new_function():
print(“Hello World”)
new_function()

Lambda Function

A lambda function is a small anonymous function. It can take any number of arguments but can only have one expression.

lambda a,b: a+b
lambda a,b: a*b

Generic Operations

In python, we have a huge a list of Python built-in functions. Some of them are:

  • range(5): 0,1,2,3,4
  • S=input(“Enter:”)
  • Len(a): Gives item count in a
  • min(a): Gives minimum value in a
  • max(a): Gives minimum value in a
  • sum(a): Adds up items of an iterable and returns sum
  • sorted(a): Sorted list copy of a
  • importing modules: import random

File Operations:

In python, we have several functions for creating, reading, updating, and deleting files. Theopen() function takes two parameters — filename, and mode.
There are four different methods (modes) for opening a file:

  • “r” — Read — Default value. Opens a file for reading, error if the file does not exist
  • “a” — Append — Opens a file for appending, creates the file if it does not exist
  • “w” — Write — Opens a file for writing, creates the file if it does not exist
  • “x” — Create — Creates the specified file, returns an error if the file exists

f= open(“File Name”,“opening mode”)

(Opening modes: r: read, w: write, a: append, r+: both read and write)

Try & Except Block:

The try block allow us to test a block of code for errors.The except block allow us to handle the error.

try:
[Statement body block]
raise Exception()
except Exception as e:
[Error processing block]

Oops Concepts

Python is an object-oriented programming language. In Python, almost everything is an object and has its own properties and methods. Here a class is like an object constructor, or a “blueprint” for creating objects.

  • Inheritance: A process of using details from a new class without modifying existing class.
  • Polymorphism: A concept of using common operation in different ways for different data input.
  • Encapsulation: Hiding the private details of a class from other objects.
Source :- https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/

Class/object Example:

Class: class Pen:
pass
object:obj=Pen()

Data Structures

Surce:- https://intellipaat.com/blog/tutorial/python-tutorial/data-structures-with-python-cheat-sheet/

The areas in which Data Structures are applied:

  • Compiler design
  • Operating system
  • Database Management System
  • Statistical Analysis Package
  • Numerical Analysis
  • Graphics
  • Artificial Intelligence
  • Simulations

Data structures used in the following areas:

  • RDBMS: Array (Array of structure)
  • Network data model: Graph
  • Hierarchical Data model: Trees

Types of Data Structures:

Primitive Data Structures:

Integer: It is used to represent numeric data, more specifically whole numbers from negative infinity to infinity.

Example: 4, 5, -1 etc

Float: It stands for floating point number

Example: 1.1,2.3,9.3 etc.

String: It is a collection of Alphabets, words or other characters. In python it can be created by using a pair of single or double quotes for the sequence

Example:

x = ‘Cake’

y = ‘’Cookie’’

Certain operations can be performed on a string:

  • We can use * to repeat the string for a specific number of times

Example: x*2

  • String can be sliced, that is to select parts of the string

Example: Coke

z1 = x[2:]
print(z1)
# Slicing
z2 = y[0] + y[1]
print(z2)
Output: ke
Co
  • To capitalize the strings

Example:

str.capitalize('cookie')
  • To retrieve the length of the strings

Example:

str1 = "Cake 4 U"
str2 = "404"
len(str1)
  • To replace parts of a string with another string

Example:

str1.replace('4 U', str2)
  • Boolean: It is a built-in data type that can take the values TRUE or FALSE

Non- Primitive Data Structures:

  • Array: It is a compact way of collecting data types where all entries must be of the same data type.

Syntax of writing an array in python:

import array as arr
a = arr.array("I",[3,6,9])
type(a)
  • Linked list: List in Python is used to store collection of heterogeneous items. It is described using the square brackets [] and hold elements separated by comma

Example:

x = [] # Empty list
type(x)

The list can be classified into linear and non-linear data structures
Linear data structures contain Stacks and queues
Non-linear data structures contain Graphs and Trees

  • Stack: It is a container of objects that can be inserted or removed according to LIFO (Last in First Out) pop() method is used during disposal in Python

Example:

stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 -> 5 (Top)
stack.pop() # Bottom -> 1 -> 2 -> 3 -> 4 (Top)
print(stack)
  • Queue: It is a container of objects that can be inserted or removed according to FIFO (First in First Out)
  • Graph: It is a data structure that consists of a finite set of vertices called nodes, and a finite set of ordered pair (u,v) called edges. It can be classified as direction and weight
  • Binary Tree: Tree is a hierarchical data structure. Here each node has at most two children
  • Binary Search Tree: It provides moderate access/ search and moderate insertion/ deletion
  • Heap: It is a complete tree and is suitable to be stored in an array, it is either MIN or Max
  • Hashing: Collection of items that are stored in a way that it becomes easy to find them is hashing

Lists and tuples (In Python):

Ordered sequence of values indexed by integer numbers. Tuples are immutable

  • To initialize empty list /tuple:

Syntax:

Lists: myList = []
Tuples: myTuple = ()
  • To specify size of tuple/list:

Syntax:

len(m­yLi­stO­rTu­ple)
  • To get an element in position x in list/tuple:

Syntax:

"x" in myList­OrT­uple
  • Index of element ‘X’ of list/tuple

Syntax:

myLis­tOr­Tup­le.i­nd­ex(­"­x") -- If not found, throws a Value­Error exception
  • Number of occurrences of X in list/tuple:

Syntax:

myLis­tOr­Tup­le.c­ou­nt(­"­x")
  • Update an item of List/tuple:

Syntax:

Lists: myList[x] = "x"
Tuples: tuples are immutable!
  • Remove element in position X of list/tuple:

Syntax:

Lists: del myList[x]
Tuples: tuples are immutable!
  • Concatenate two lists/tuples:
Lists: myList1 + myList2
Tuples: myTuple1 + myTuple2
Concatenating a List and a Tuple will produce a TypeE­rror exception
  • Insert element in position x of a list/t­uple

Syntax:

Lists: myLis­t.i­nse­rt(x, "value")
Tuples: tuples are immutable!
  • Append “­x” to a list/t­uple:
Syntax: Lists: myList.append("x")
Tuples: tuples are immutable!
  • Convert a list/tuple to tuple/list:
Syntax: List to Tuple: tuple(myList)
Tuple to List: list(­myT­uple)

Sets:

It is an unordered collection with no duplicate elements. It supports mathematical operations like union, inters­ection, difference and symmetric differ­ence.

  • To initialize an empty set:
Syntax: mySet = set()
  • Initialize a non-empty set
Syntax: mySet = set(el­ement1, elemen­t2...)
  • To add element X to the set
Syntax: mySet.ad­d("x­")
  • Remove element “­x” from a set:

Syntax:

Method 1: mySet.re­mov­e("x­") -- If "­x" is not present, raises a KeyErorr
Method 2: mySet.di­sca­rd(­"­x") -- Removes the element, if present
  • Remove every element from the set
Syntax: mySet.cl­ear()
  • Check if “­x” is in the set
Syntax: "x" in mySet
  • Union of two sets

Syntax:

Method 1: mySet1.union(mySet2)
Method 2: mySet1 | mySet2
  • Inters­ection of two sets

Syntax:

Method 1: mySet1.intersect(mySet2)
Method 2: mySet1 & mySet2
  • Difference of two sets

Syntax:

Method 1: mySet1.difference(mySet2)
Method 2: mySet1 - mySet2
  • Symmetric difference of two sets

Syntax:

Method 1: mySet1.symmetric_difference(mySet2)
Method 2: mySet1 ^ mySet2
  • Size of the sets:

Syntax:

len(m­ySet)

Dictionaries:

It is an unordered set of key value pairs

  • Initialize an empty Dict

Syntax:

myDict = {}
  • Add an element with key “­k” to the Dict

Syntax:

myDic­t["k­"] = value
  • Update the element with key “­k”

Syntax:

myDic­t["k­"] = newValue
  • Get element with key “­k”

Syntax:

myDic­t["k­"] -- If the key is not present, a KeyError is raised
  • Check if the dictionary has key “­k”

Syntax:

"k" in myDict
  • Get the list of keys

Syntax:

myDic­t.k­eys()
  • Get the size of the dictionary

Syntax:

len(m­yDict)
  • Delete element with key “­k” from the dictionary

Syntax:

del myDict­["k"]
  • Delete all the elements in the dictionary

Syntax:

myDic­t.c­lear()

Algorithms and the complexities:

AlgorithmBest caseAverage caseWorst caseRemarksSelection sort½ nnn 2n exchanges,
quadratic is the best caseInsertion sortn¼ nn 2Used for small or partial-sorted arraysBubble sortn½ nn 2Rarely useful,
Insertion sort can be used insteadShell sortn log3 nunknownc n 3/2Tight code,
Sub quadraticMerge sort½ n lg nn lg nn lg nn log n guarantee;
stableQuick sortn lg n2 n ln n½ n 2n log n probabilistic guarantee;
fastest in practiceHeap sortn †2 n lg n2 n lg nn log n guarantee;
in place

Symbol Table:

Flask — Web app development Framework

https://www.idiotinside.com/uploads/2015/02/flask-cheat-sheet.pdf

--

--

Speedster Saurabh

Don’t be intimidated by jargon. For example, a model is just a fancy word for “recipe.”