Python Cheat Sheet
Transform, format, and optimize your data instantly with this free client-side tool.
Basics
Variable assignment
Get the data type of x
Print variables to the console
Read a string from standard input
Convert a string to an integer
Convert an integer to a string
Get the length of an object (list, string, etc.)
List attributes and methods of an object
Control Flow
If statement
Else if statement
Else statement
For loop iterating from 0 to 4
Iterate over elements in an iterable
While loop
Break out of the closest enclosing loop
Skip to the next iteration of the loop
Null operation (placeholder)
Strings
String definition
Convert string to uppercase
Convert string to lowercase
Replace occurrences of 'a' with 'b'
Split string into list by delimiter
Join elements of a list into a string
Remove leading and trailing whitespace
f-string formatting (Python 3.6+)
Check if string starts with 'A'
Lists
List definition
Add item to the end of the list
Insert x at index 1
Remove and return the last item
Remove the first occurrence of x
Sort the list in-place
Reverse the list in-place
List slicing: elements from index 1 to 2
List comprehension
Dictionaries
Dictionary definition
Access value by key
Get value for 'c', return 0 if not found
Get all keys in the dictionary
Get all values in the dictionary
Get key-value pairs as tuples
Update dictionary with items from d2
Delete item with key 'a'
Sets & Tuples
Tuple definition (immutable)
Set definition (unordered, unique)
Add element to set
Remove element from set
Union of two sets
Intersection of two sets
Functions
Function definition
Function with default arguments
Function accepting variable positional arguments
Function accepting variable keyword arguments
Anonymous (lambda) function definition
Return a generator
Classes
Class definition
Constructor method
Set instance attribute
Call parent class constructor
Decorator for class methods
Decorator for static methods
File Handling
Open file safely using context manager
Read entire file contents
Read a single line from file
Read all lines into a list
Write string to file
Move cursor to beginning of file
Exceptions
Start try block
Catch specific exception
Catch generic exception
Block always executed after try/except
Raise an exception manually
Modules
Import a module
Import module with alias
Import specific name from module
Install a package (Jupyter/Colab)
Install a package from terminal
Check if module is run directly
Advanced
Increase recursion depth limit
Drop into the Python debugger natively
Apply a lambda function to a list efficiently
🔥 Similar Tools
Explore LibraryFrequently Asked Questions
Got questions? We've got answers.