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 Page | help() |
Function Help | help(str.replace) |
Module Help | help(re) |
MODULE (AKA LIBRARY)
The python module is simply a '.py' file
List Module Contents | dir(module1) |
Load Module | import module1 * |
Call Function from Module | module1.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
- int/long* - Large int automatically converts to long
- float* - 64 bits, there is no 'double' type
- bool* - True or False
- 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)
- 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 :
- • None is a reserved keyword but rather a unique instance of 'NoneType'
- DateTime - built-in python 'datetime' module provides 'datetime', 'date', 'time' types.
• 'DateTime combines information stored in 'date' and 'time'Create datetime from String dt1 = datetime. strptime('20091031', '%Y%m%d') Get 'date' object dt1.date() Get 'time' object dt1.time() Format datetime to String dt1.strftime('%m/%d/%Y %H:%M') Change Field Value dt2 = dt1.replace(minute = 0, second = 30) Get Difference diff = 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 Tuple | tup1 = 4, 5, 6 or tup1 = (6,7,8) |
Create Nested Tuple | tup1 = (4,5,6), (7,8) |
Convert Sequence or Iterator to Tuple | tuple([1, 0, 2]) |
Concatenate Tuples | tup1 + tup2 |
Unpack Tuple | a, b, c = tup1 |
Application of Tuple
Swap variables | b, a = a, b |
LIST
One dimensional, variable length, mutable (i.e. contents can be modified) sequence of Python objects of ANY type.
Create List | list1 = [1, 'a', 3] or list1 = list(tup1) |
Concatenate Lists | list1 + list2 or list1.extend(list2) |
Append to End of List | list1.append('b') |
Insert to Specific Position | list1.insert(posIdx, 'b') |
Inverse of Insert | valueAtIdx = list1. pop(posIdx) |
Remove First Value from List | list1.remove('a') |
Check Membership | 3 in list1 => True |
Sort List | list1.sort() |
Sort with User Supplied Function | list1.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 Dict | dict1 = {'key1' :'value1', 2 :[3, 2]} |
Create Dict from Sequence | dict(zip(keyList, valueList)) |
Get/Set/Insert Element | dict1['key1']* dict1['key1'] = 'newValue' |
Get with Default Value | dict1.get('key1', defaultValue) |
Check if Key Exists | 'key1' in dict1 |
Delete Element | del dict1['key1'] |
Get Key List | dict1.keys() |
Get Value List | dict1.values() |
Update Values | dict1.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 Set | set([3, 6, 3]) or {3, 6, 3} |
Test Subset | set1.issubset (set2) |
Test Superset | set1.issuperset (set2) |
Test sets have same content | set1 set2 |
Set operations
Union(aka 'or') | set1 | set2 |
Intersection (aka 'and') | set1 & set2 |
Difference | set1 - 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
- All functions are local to the module-level scope. See the 'Module' section.
- 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 object | var1 is var2 |
are different object | var1 is not var2 |
Check if two variables have the same value | var1 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 iterator | for 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.
- 'object' is the root of all Python types
- 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.
- 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
- 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
- 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.