320 x 50 Mobile Ad
Cheat Sheets

Python Cheat Sheet

Transform, format, and optimize your data instantly with this free client-side tool.

Basics

x = 5

Variable assignment

type(x)

Get the data type of x

print(x, y)

Print variables to the console

input('Enter: ')

Read a string from standard input

int('5')

Convert a string to an integer

str(10)

Convert an integer to a string

len(my_list)

Get the length of an object (list, string, etc.)

dir(obj)

List attributes and methods of an object

Control Flow

if x > 5: ...

If statement

elif x == 5: ...

Else if statement

else: ...

Else statement

for i in range(5): ...

For loop iterating from 0 to 4

for item in iter: ...

Iterate over elements in an iterable

while x > 0: ...

While loop

break

Break out of the closest enclosing loop

continue

Skip to the next iteration of the loop

pass

Null operation (placeholder)

Strings

s = 'hello'

String definition

s.upper()

Convert string to uppercase

s.lower()

Convert string to lowercase

s.replace('a', 'b')

Replace occurrences of 'a' with 'b'

s.split(',')

Split string into list by delimiter

'-'.join(list)

Join elements of a list into a string

s.strip()

Remove leading and trailing whitespace

f'{var} name'

f-string formatting (Python 3.6+)

s.startswith('A')

Check if string starts with 'A'

Lists

lst = [1, 2, 3]

List definition

lst.append(4)

Add item to the end of the list

lst.insert(1, x)

Insert x at index 1

lst.pop()

Remove and return the last item

lst.remove(x)

Remove the first occurrence of x

lst.sort()

Sort the list in-place

lst.reverse()

Reverse the list in-place

lst[1:3]

List slicing: elements from index 1 to 2

[x*2 for x in lst]

List comprehension

Dictionaries

d = {'a': 1, 'b': 2}

Dictionary definition

d['a']

Access value by key

d.get('c', 0)

Get value for 'c', return 0 if not found

d.keys()

Get all keys in the dictionary

d.values()

Get all values in the dictionary

d.items()

Get key-value pairs as tuples

d.update(d2)

Update dictionary with items from d2

del d['a']

Delete item with key 'a'

Sets & Tuples

t = (1, 2, 3)

Tuple definition (immutable)

st = {1, 2, 3}

Set definition (unordered, unique)

st.add(4)

Add element to set

st.remove(1)

Remove element from set

st1.union(st2)

Union of two sets

st1.intersection(st2)

Intersection of two sets

Functions

def func(arg): return arg

Function definition

def func(a, b=2): ...

Function with default arguments

def func(*args): ...

Function accepting variable positional arguments

def func(**kwargs): ...

Function accepting variable keyword arguments

lambda x, y: x + y

Anonymous (lambda) function definition

yield x

Return a generator

Classes

class MyClass: ...

Class definition

def __init__(self): ...

Constructor method

self.attr = x

Set instance attribute

super().__init__()

Call parent class constructor

@classmethod

Decorator for class methods

@staticmethod

Decorator for static methods

File Handling

with open('f.txt', 'r') as f:

Open file safely using context manager

f.read()

Read entire file contents

f.readline()

Read a single line from file

f.readlines()

Read all lines into a list

f.write('text')

Write string to file

f.seek(0)

Move cursor to beginning of file

Exceptions

try: ...

Start try block

except ValueError as e: ...

Catch specific exception

except Exception as e: ...

Catch generic exception

finally: ...

Block always executed after try/except

raise ValueError('msg')

Raise an exception manually

Modules

import math

Import a module

import nump as np

Import module with alias

from math import pi

Import specific name from module

!pip install pkg

Install a package (Jupyter/Colab)

python -m pip install pkg

Install a package from terminal

__name__ == '__main__'

Check if module is run directly

Advanced

sys.setrecursionlimit(2000)

Increase recursion depth limit

import pdb; pdb.set_trace()

Drop into the Python debugger natively

list(map(lambda x: x*2, nums))

Apply a lambda function to a list efficiently

320 x 50 Mobile Ad

Frequently Asked Questions

Got questions? We've got answers.

The Python Cheatsheet is a quick-reference guide that provides developers with the most essential and frequently used Python commands, syntax, and snippets in one centralized place.
This reference is built for both beginners who are just learning Python and need a quick syntax lookup, as well as seasoned professionals who need to jog their memory on complex commands.
You can use the real-time search bar at the top of the cheatsheet. Simply type a keyword (like 'delete' or 'file') and the list will instantly filter to show only matching Python commands.
Yes! Every command block features a one-click copy button. Just hover over the command and click the copy icon to instantly send the snippet to your clipboard.
The cheatsheet is divided into logical categories such as Basics, Network, Operations, and specific Python features. You can click on the category filters at the top to isolate specific groups of commands.
Absolutely. This Python reference guide is 100% free, requiring no sign-ups or subscriptions, and is always available when you need it.
While these are standard Python operations, you should always understand what a command does before running it, especially if it involves system operations or destructive actions.
Yes, we have recently expanded this cheatsheet to include advanced snippets, best practices, and edge-case syntax that go beyond basic introductory commands.
ADVERTISEMENT
Boost Your Business Online