Oop Python Cheat Sheet



We created this Python 3 Cheat Sheet initially for students of Complete Python Developer in 2021: Zero to Mastery but we're now sharing it with any Python beginners to help them learn and remember common Python syntax and with intermediate and advanced Python developers as a handy reference. If you'd like to download a PDF version of this Python Cheat Sheet, enter your email below and we'll.

Python cheat sheet enables users of Python with quicker operations and more ease of use. Python is a widely used high-level programming language created by Guido van Rossum in the late 1980s. So today I am going to tell you all the secret shortcuts and all cheat codes to make your speed 4x in python coding.

Object-Oriented programming is a widely used concept to write powerful applications. As a data scientist, you will be required to write applications to process your data, among a range of other things. In this tutorial, you will discover the basics of object-oriented programming in Python. You will learn the following: How to create a class. Use this cheat sheet as a guide in the beginning and come back to it when needed, and you’ll be well on your way to becoming a pro programmer in Python. Join my email list with 1k+ people to get The Complete Python for Data Science Cheat Sheet Booklet for Free.

Python All Shortcuts and Cheat Sheets

Python General Shortcuts

  • Python is case sensitive
  • Python index starts from 0
  • Python uses whitespace (tabs or spaces) to indent instead of using braces.

HELP

Help Home Pagehelp()
Function Helphelp(str.replace)
Module Helphelp(re)

MODULE (AKA LIBRARY)

Examples

The python module is simply a '.py' file

List Module Contentsdir(module1)
Load Moduleimport module1 *
Call Function from Modulemodule1.func1()
  • import statement creates a new namespace and executes all the statements in the associated .py file within that namespace. If you want to load the module's content into the current namespace, use 'from module1 import

Python Scaler Type Shortcuts

Check data type : type(variable)

Python SIX COMMONLY USED DATA TYPES

  1. int/long* - Large int automatically converts to long
  2. float* - 64 bits, there is no 'double' type
  3. bool* - True or False
  4. str* - ASCII valued in Python 2.x and Unicode in Python
    • The string can be in single/double/triple quotes
    • The string is a sequence of characters, thus can be treated like other sequences
    • Special character can be done via or preface with r
      • str1 = r'thisf?ff'
    • String formatting can be done in a number of ways
    • template = '%.2f %s haha $%d';
      str1 = template % (4.88, 'hola', 2)
  5. NoneType(None) - Python 'null' value (ONLY one instance of None object exists)
    • • None is a reserved keyword but rather a unique instance of 'NoneType'
      • None is the common default value for optional
      function arguments :
      def func1(a, b, c = None)
      • Common usage of None :
      if the variable is None :
  6. DateTime - built-in python 'datetime' module provides 'datetime', 'date', 'time' types.
    • 'DateTime combines information stored in 'date' and 'time'
    • Create datetime from Stringdt1 = datetime. strptime('20091031', '%Y%m%d')
      Get 'date' objectdt1.date()
      Get 'time' objectdt1.time()
      Format datetime to Stringdt1.strftime('%m/%d/%Y %H:%M')
      Change Field Valuedt2 = dt1.replace(minute = 0, second = 30)
      Get Differencediff = dt1 - dt2 # diff is a 'datetime.timedelta' object
    • Note : Most objects in Python are mutable except for 'strings' and 'tuples'

Python Data Structures

All non-Get function calls i.e. list1.sort() examples below are in-place (without creating a new object) operations unless noted otherwise.

TUPLE

One dimensional, fixed-length, immutable sequence of Python objects of ANY type.

Create Tupletup1 = 4, 5, 6 or tup1 = (6,7,8)
Create Nested Tupletup1 = (4,5,6), (7,8)
Convert Sequence or Iterator to Tupletuple([1, 0, 2])
Concatenate Tuplestup1 + tup2
Unpack Tuplea, b, c = tup1

Application of Tuple

Swap variablesb, a = a, b

LIST

One dimensional, variable length, mutable (i.e. contents can be modified) sequence of Python objects of ANY type.

Create Listlist1 = [1, 'a', 3] or list1 = list(tup1)
Concatenate Listslist1 + list2 or list1.extend(list2)
Append to End of Listlist1.append('b')
Insert to Specific Positionlist1.insert(posIdx, 'b')
Inverse of InsertvalueAtIdx = list1. pop(posIdx)
Remove First Value from Listlist1.remove('a')
Check Membership3 in list1 => True
Sort Listlist1.sort()
Sort with User Supplied Functionlist1.sort(key = len) # sort by length
  • List concatenation using '+' is expensive since a new list must be created and objects copied over. Thus, extend() is preferable.
  • Insert is computationally expensive compared with append.
  • Checking that a list contains a value is a lot slower than Dict and sets as Python makes a linear scan where others (based on hash tables) in constant time.

Built-in 'bisect module

  • Implements binary search and insertion into a sorted list
  • 'bisect. bisect' finds the location, where 'bisect. insert actually inserts into that location.

WARNING: bisect module functions do not check whether the list is sorted, doing so would be computationally expensive. Thus, using them in an unsorted list will succeed without error but may lead to incorrect results.

SLICING FOR SEQUENCE TYPES

Sequence types include 'str', 'array', 'tuple', 'list', etc.

Notation

list1[start:stop]

list1[start:stop:step] (If step is used)

NOTE:

  • The 'start' index is included, but the 'stop' index is NOT.
  • start/stop can be omitted in which they default to the start/end.

Application of 'step' :

  • Take every other element list1[::2]
  • Reverse a string str1[::-1]

DICT (HASH MAP)

Create Dictdict1 = {'key1' :'value1', 2 :[3, 2]}
Create Dict from Sequencedict(zip(keyList, valueList))
Get/Set/Insert Elementdict1['key1']* dict1['key1'] = 'newValue'
Get with Default Valuedict1.get('key1', defaultValue)
Check if Key Exists'key1' in dict1
Delete Elementdel dict1['key1']
Get Key Listdict1.keys()
Get Value Listdict1.values()
Update Valuesdict1.update(dict2) # dict1 values are replaced by dict2
  • 'KeyError' exception if the key does not exist.
  • 'get()' by default (aka no 'defaultValue') will return 'None' if the key does not exist.
  • Returns the lists of keys and values in the same order. However, the order is not any particular order, aka it is most likely not sorted.

Valid Dict key types

  • Keys have to be immutable like scalar types (int, float, string) or tuples (all the objects in the tuple need to be immutable too)
  • The technical term here is 'hash ability, check whether an object is hashable with the hash('this is a string'), hash([1, 2]) - this would fail.

SET

  • A set is an unordered collection of UNIQUE elements.
  • You can think of them like Dicts but keys only.
Create Setset([3, 6, 3]) or {3, 6, 3}
Test Subsetset1.issubset (set2)
Test Supersetset1.issuperset (set2)
Test sets have same contentset1 set2

Set operations

Union(aka 'or')set1 | set2
Intersection (aka 'and')set1 & set2
Differenceset1 - set2
Symmetric Difference (aka 'xor')set1 ^ set2

Functions

Python is passed by reference, function arguments are passed by reference.

• Basic Form :

NOTE:

  • Keyword arguments MUST follow positional arguments.
  • Python by default is NOT 'lazy evaluation', expressions are evaluated immediately.

Function Call Mechanism

  1. All functions are local to the module-level scope. See the 'Module' section.
  2. Internally, arguments are packed into a tuple and Dict, the function receives a tuple 'args' and Dict 'kwargs' and internally unpack.
Common usage of 'Functions are objects'

RETURN VALUES

  • None is returned if the end of the function is reached without encountering a return statement.
  • Multiple values return via ONE tuple object

ANONYMOUS (AKA LAMBDA) FUNCTIONS

Python Oop Cheat Sheet Pdf

What is Anonymous function?

  • A simple function consisting of a single statement.

#def func1(x) : return x * 2

Application of lambda functions: 'curring' aka deriving new functions from existing ones by partial argument application.

USEFUL FUNCTIONS (FOR DATA STRUCTURES)

There are 4 Useful functions for data structures

Enumerate returns a sequence (i, value) tuples where i is the index of the current item.

Application: Create a Dict mapping of the value of a sequence (assumed to be unique) to their locations in the sequence.

Sorted returns a new sorted list from any sequence

returns sorted unique characters

Zip pairs up elements of a number of lists, tuples, or other sequences to create a list of tuples

  • Zip can take an arbitrary number of sequences. However, the number of elements it produces is determined by the 'shortest' sequence.
  • Application: Simultaneously iterating over multiple sequences
  • Unzip - another way to think about this is converting a list of rows to a list of columns.

Reversed iterates over the elements of a sequence in reverse order.

  • reversed() returns the iterator, list() makes it a list.

Control and Flow

1. Operators for conditions in 'if else' :

Check if two variables are the same objectvar1 is var2
are different objectvar1 is not var2
Check if two variables have the same valuevar1 var2

WARNING: Use 'and', 'or', 'not' operators for compound conditions, not &&, ||, !.

2. Common usage of 'for' operator

Iterating over a collection (i.e. list or tuple) or an iteratorfor element in an iterator
If elements are sequences, can be 'unpack'for a, b, c in iterator

3. 'pass' - no-op statement. Used in blocks where n action is to be taken.

4. Ternary Expression - aka less verbose 'if else'

  • Basic Form :

5. No switch/case statement, use if/elif instead.

Python Object-Oriented Programming

There are ways to do this.

  1. 'object' is the root of all Python types
  2. Everything (number, string, function, class, module, etc.) is an object, each object has a 'type'. Object variable is a pointer to its location in memory.
  3. All objects are reference-counted.

Python Basic Syntax Sheet Pdf

4. Class Basic Form

5. Useful interactive tool

Common String operations

There are 5 common string Operators

  1. Concatenate List/Tuple with Separator

2. Format String

3. Split String

4. Get Substring

5. String Padding with Zeros

Exception Handling

1. Basic Form

2. Raise Exception Manually

List, Set, and Dict Comprehensions

Syntactic sugar that makes code easier to read and write

  1. List comprehensions
    • Concisely form a new list by filtering the elements of a collection and transforming the elements passing the filter into one concise expression.

Basic form :

A shortcut for :

The filter condition can be omitted, leaving only the expression.

2. Dict Comprehension

  • Basic form

3. Set Comprehension

Basic form: same as List Comprehension except with curly braces instead of []

4. Nested list Comprehensions

Oop Python Cheat Sheet Download

  • Basic form

Oop Python Cheat Sheet Pdf

Thank you for reading this post. If you were like this post then please tell us which shortcut you like most and anything I forget to add in this post then please tell us in the comments thank you.