Python Cheat Sheet
A quick reference for Python syntax, data structures, and common functions.
2 PagesBeginnerMay 20, 2026
Variables
Variables are used to store data values.
python
x = 10 # Integername = "SkillVeris" # Stringprice = 19.99 # Floatis_active = True # Boolean
Data Types
Python has the following built-in data types.
- int- Whole numbers
- float- Decimal numbers
- str- Text (string)
- bool- True or False
- list- Ordered collection
- tuple- Immutable ordered collection
- dict- Key-value pairs
- set- Unordered collection
List Operations
Common operations on lists.
python
fruits = ["apple", "banana", "cherry"]fruits.append("orange") # Add itemfruits.remove("banana") # Remove itemfirst = fruits[0] # Access itemlength = len(fruits) # Length of list
Dictionary Ops
Working with key-value pairs.
python
person = {"name": "Alice", "age": 30}person["email"] = "[email protected]"name = person.get("name") # Get safelydel person["age"] # Delete keykeys = list(person.keys()) # All keys
Functions
Define reusable blocks of code.
python
def greet(name, greeting="Hello"): return f"{greeting}, {name}!"# Lambda (anonymous function)square = lambda x: x ** 2print(square(5)) # 25
Comprehensions
Build lists, sets, and dicts inline.
python
squares = [x**2 for x in range(10)]evens = [x for x in range(20) if x % 2 == 0]matrix = [[r*c for c in range(3)] for r in range(3)]unique = {c.lower() for c in "Hello"}lengths = {w: len(w) for w in ["hi", "world"]}gen = (x*x for x in range(5)) # lazy generator
String Methods & F-Strings
Common string formatting and manipulation.
python
name, score = "Ada", 97.5print(f"{name}: {score:.1f}%") # Ada: 97.5%print(f"{score:>8.2f}") # right-align width 8"a,b,c".split(",") # ['a', 'b', 'c']"-".join(["a", "b"]) # 'a-b'" hi ".strip() # 'hi'"Hello".replace("l", "L") # 'HeLLo'"abc".startswith("ab") # True
Exception Handling
try/except/else/finally and raising errors.
python
try: value = int(user_input)except ValueError as e: print(f"Bad input: {e}")except (KeyError, IndexError): print("Lookup failed")else: print("Parsed OK") # runs if no exceptionfinally: print("Always runs")if value < 0: raise ValueError("must be non-negative")
Classes & Dataclasses
Define objects with methods and dataclasses.
python
from dataclasses import dataclass, field@dataclassclass Point: x: int y: int tags: list = field(default_factory=list) def dist(self) -> float: return (self.x**2 + self.y**2) ** 0.5p = Point(3, 4)print(p.dist()) # 5.0print(p) # Point(x=3, y=4, tags=[])
Useful Built-ins
High-value built-in functions to know.
- enumerate(it)- yields (index, value) pairs while looping
- zip(a, b)- pairs items from multiple iterables together
- sorted(it, key=)- returns a new sorted list; key controls ordering
- map/filter- apply a function or keep items matching a predicate
- any/all- True if any / all elements are truthy
- sum/min/max- aggregate numeric iterables; accept a key= for min/max
Pro Tip
Use built-in functions and list comprehensions to write clean and efficient Python code.
Was this cheat sheet helpful?
Explore Topics
#Python#PythonCheatSheet#Programming#Beginner#Variables#DataTypes#ListOperations#DictionaryOps#Functions#CheatSheet#SkillVeris