Python Basics Cheat Sheet — Syntax Reference

Variables, strings, lists, loops & functions — every Python basic with copy-ready code.

A free, searchable Python basics cheat sheet covering variables & data types (with mutable vs immutable explained), strings (f-strings, slicing, common methods), lists, sets, dictionaries & tuples, control flow (if/elif/else, operators), loops (for, while, range, enumerate, zip), functions (default args, *args/**kwargs, lambda), full error handling (try/except/finally/raise), file handling (open/read/write with the with statement), the basics of classes & objects (__init__, self, methods) and common built-ins & modules (print/input, import, map/filter) — each with a copy-ready snippet and a real worked example showing the actual output. Includes a quick-reference table comparing List vs Tuple vs Set vs Dict. Runs fully in your browser, no sign-up, no API.

About Python Basics Cheat Sheet — Syntax Reference

Python Basics Cheat Sheet — Syntax Reference features

Best practices

f-strings can run expressions, not just variables

Anything inside the { } of an f-string is evaluated as real Python code — f"{2 + 2}" prints 4, and f"{name.upper()}" calls a method right there.

Negative indexes count from the end

fruits[-1] gets the last item in a list, fruits[-2] the second-to-last — no need to calculate len(fruits) - 1 yourself.

Swap two variables without a temp variable

a, b = b, a swaps the values of a and b in one line — Python evaluates the right-hand side as a tuple first, then unpacks it.

Indentation must be consistent within a block

Mixing tabs and spaces, or using a different number of spaces on sibling lines, raises an IndentationError. Most editors (and this site's own tools) default to 4 spaces per level — stick to one style throughout a file.

Frequently asked questions

Is Python good for beginners?

Yes — Python is one of the most beginner-friendly languages because its syntax reads close to plain English, it doesn't require declaring variable types, and it has a huge standard library and community, so almost any problem you run into already has a documented answer.

What is the difference between a list and a tuple?

Both store an ordered collection of items, but a list (written with [ ]) can be changed after creation — items added, removed or updated — while a tuple (written with ( )) is immutable, meaning it can never be modified once created. Use a tuple for fixed data that shouldn't change.

What is an f-string in Python?

An f-string is a string prefixed with f that lets you insert variables or expressions directly inside curly braces, like f"{name} is {age} years old". It's the modern, most readable way to build strings with dynamic content in Python.

What is a list comprehension?

A list comprehension is a compact, one-line way to build a new list by transforming or filtering an existing one — [n * n for n in numbers] squares every number in numbers, and [n for n in numbers if n % 2 == 0] keeps only the even ones.

How do I loop through a dictionary in Python?

Use .items() to get both the key and value together: for key, value in my_dict.items(): — or .keys() / .values() if you only need one side. Looping directly over a dictionary (for key in my_dict:) gives you just the keys.

What does *args and **kwargs mean in a Python function?

*args lets a function accept any number of extra positional arguments, collected into a tuple. **kwargs does the same for extra named (keyword) arguments, collected into a dictionary. They're used when you don't know in advance how many arguments will be passed in.

What is the difference between mutable and immutable in Python?

A mutable type (list, dict, set) can be changed in place after creation — you can add, remove or update its contents directly. An immutable type (string, number, tuple) can never be changed once created; any operation that looks like it modifies one, like a string's .upper(), actually returns a brand-new value instead.

When should I use a set instead of a list?

Use a set when you only care about unique values (it automatically removes duplicates) or need to check whether a value exists as fast as possible. Use a list when order matters, you need duplicates, or you'll access items by their numeric position.

How do I read and write files in Python?

Use with open("file.txt", "r") as f: to read (f.read() for the whole file, or loop over f for line by line), and with open("file.txt", "w") as f: f.write("text") to write — "w" overwrites the file, "a" appends instead. The with statement closes the file automatically, even if an error happens.

How do I create a class in Python?

Start with class ClassName:, then define __init__(self, ...) — a special method that runs automatically when you create a new object, used to set up its starting data via self.attribute = value. Any other function defined inside the class becomes a method, callable on objects created from it.

Why does Python use indentation instead of curly braces?

Python's designers made indentation part of the syntax itself, forcing consistently readable code — instead of { } marking a block, the indented lines underneath an if, for, while or def ARE the block. Inconsistent indentation raises an IndentationError.

What is the difference between == and = in Python?

A single = assigns a value to a variable (x = 5 stores 5 in x). A double == compares two values for equality and returns True or False (x == 5 checks whether x currently equals 5).

How do I handle errors in Python?

Wrap the risky code in a try block, and catch the specific error in an except block — try: result = 10 / 0 except ZeroDivisionError: print("Can't divide by zero"). This lets your program respond gracefully instead of crashing.

What is the difference between append() and insert() for lists?

append(item) always adds the item to the very end of the list. insert(index, item) adds it at a specific position you choose, shifting every item after it one place to the right.

Is this Python cheat sheet free to use?

Yes — it is 100% free with no sign-up, no login and no limits. The whole reference runs in your browser, so you can search, read and bookmark it without creating an account.

Related tools — Guides & Tutorials