Hello fellow Finxters! I am back with another installment of top 10 cheat sheets. This time, we will be compiling a list of Python Object Oriented Programming (OOP) cheat sheets to make it easier to write programs to keep on hand! Let us dig right in without wasting any more time!

💎 Cheat sheet to prep for technical interviews. Topics java computer-science algorithms guide data-structures cheatsheet interviews software-engineering coding-interviews interview-preparation technical-interviews. Python Cheat Sheet just the basics Created By: arianne Colton and Sean Chen. Data structures Note:. 'start' index is included, but '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). Python Cheat Sheet: Python is a multi-paradigm general-purpose, object-oriented programming languageIt is a cross-platform programming language.

Here’s the cheat sheet created by Finxters—downloadable as a simple, plain PDF:

Cheat Sheet 1: Piazza

This 7-page cheat sheet is one to keep handy on the desk when you are first trying to understand OOP in Python. It has full explanations and examples giving you a full scope of classes, inheritance, and naming conventions for best practices. It perfect for beginners and those who need a refresher.

Pros: Rated ‘E’ for everyone. This cheat sheet is great for everyone.

Cons: It can be a lengthy read; I would suggest highlighting the parts you really need.

Cheat Sheet 2: Codecademy

Codecademy is great place to learn coding in general. This cheat sheet shows you about classes and methods used to perform certain action in your programming. By visiting this link, you will also have access to other cheat sheets for functions, control flow, and other topics. It is perfect for beginners, it has explanations with code examples to show you how the method works.

Pros: Rated ‘E’ for everyone.

Cons: None that I can see.

Cheat Sheet 3: Intellipaat

This cheat sheet goes over the basics of Python neatly separated into little boxes. It is great if you just need a quick reminder. This cheat sheet however has minimal explanation and no examples. I would leave this one to intermediate Pythoniers.

Pros: Easy to read and understand.

Cons: No examples to see how the method runs

Cheat Sheet 4: Hackin9

Taken from Python crash course by nostrachpress.com. This cheat sheet is 27 pages and covers Python 2 and 3. Complete with explanations that take you from the basics to Django. This cheat sheet is one you will want to keep handy! I know I do, tagged and highlighted!

Oop Python Cheat Sheet

Pros: Covers everything you need to know about Python.

Cons: It is a lengthy read.

Cheat Sheet 5: Tutorials Point

Tutorials Point is a great place to start if you want to learn Python! This cheat sheet is straight to the point, done in black and white. It has explanations and examples. It is great for the beginner Pythonier.

Pros: Rated ‘E’ for everyone. Contains all the information you need.

Cons: It is a lengthy read, 8 pages in length.

Cheat Sheet 6: ISU Computer Science

From ISU Computer Science, this cheat sheet has all the Python keywords, concepts and functions. It is a great quick guide, though I would say for intermediate Pythoniers who do not need a lot of explanation.

Pros: Easy to read and understand

Cons: Not for beginners.

Cheat Sheet 7: CodeGrepper

CodeGrepper is a wonderful chrome extension made for beginner and advanced developers allowing you to spend more time developing and less time searching for answers. This cheat sheet gives you a code example explanation on the various methods in OOP for Python.

Pros: Rated ‘E’ for everyone.

Cons: None that I can see.

Cheat Sheet 8: Programming with Mosh

This quick cheat sheet gets straight to the point with code examples. It is a good one to keep pinned above the monitor.

Pros: Rated ‘E’ for everyone. Easy to understand.

Cons: None that I can see.

Oop Python Cheat Sheet

Cheat Sheet 9: Website Setup

This cheat sheet is one to keep handy as you are developing your app! Highlight most commonly used functions and have an in depth understanding of Python OOP.

Pros: Rated ‘E’ for everyone. One to keep on hand for sure!

Cons: It is a lengthy read.

Cheat Sheet 10: Techgeekbuzz

This cheat sheet will introduce Python and give code examples on the different methods and functions in Python.

Pros: Rated ‘E’ for everyone

Cons: None that I can see.

Bonus Cheat Sheet: Real Python

I found this cheat sheet last minute and even though it is not an actual cheat sheet for OOP syntax it is a cheat sheet of the best resources to learn OOP in Python. I have each one bookmarked in my browser so I can understand OOP better myself!

Related Articles:

Related Posts

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.

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)

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

Sheet

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

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.

4. Class Basic Form

Oop Python Cheat Sheet Pdf

5. Useful interactive tool

Common String operations

There are 5 common string Operators

Cheat
  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

Best Python Cheat Sheet Pdf

Oop Python Cheat Sheet

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

Python Cheat Code

  • Basic form

3. Set Comprehension

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

4. Nested list Comprehensions

  • Basic form

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.