Contents

Python Cheatsheet Every Learner Must Know

Python is one of the most versatile and beginner-friendly programming languages. Whether you’re just starting out or looking to refresh your memory, this comprehensive cheatsheet will save you hours of time searching for syntax and common patterns. Keep this guide handy as your quick reference!

📊 Quick Reference Table

CategoryConceptSyntaxExample
VariablesAssignmentx = 5 
 Multiple assignmenta, b = 1, 2 
Data TypesStringtext = "Hello" 
 Integernum = 42 
 Floatpi = 3.14 
 Booleanis_true = True 
 Listitems = [1, 2, 3] 
 Tuplecoords = (x, y) 
 Dictionarydata = {"key": "value"} 
 Setunique = {1, 2, 3} 
String OperationsConcatenation"Hello" + " World" 
 Repetition"Ha" * 3 
 Slicingtext[0:5] 
 Lengthlen(text) 
 Upper/Lowertext.upper() / text.lower() 
 Strip whitespacetext.strip() 
 Replacetext.replace("old", "new") 
 Splittext.split(",") 
 Join", ".join(list) 
List OperationsAppendlist.append(item) 
 Extendlist.extend([1, 2]) 
 Insertlist.insert(0, item) 
 Removelist.remove(item) 
 Poplist.pop() / list.pop(index) 
 Indexlist.index(item) 
 Countlist.count(item) 
 Sortlist.sort() / sorted(list) 
 Reverselist.reverse() 
 List comprehension[x*2 for x in list] 
Dictionary OperationsAccess valuedict["key"] 
 Get with defaultdict.get("key", default) 
 Add key-valuedict["new"] = "value" 
 Remove keydel dict["key"] 
 Get keysdict.keys() 
 Get valuesdict.values() 
 Get itemsdict.items() 
 Check key exists"key" in dict 
Control FlowIf statementif condition: 
 If-elseif condition: else: 
 If-elif-elseif: elif: else: 
 For loopfor item in iterable: 
 While loopwhile condition: 
 Breakbreak 
 Continuecontinue 
Loops & IterationRangefor i in range(5): 
 Enumeratefor i, val in enumerate(list): 
 Zipfor a, b in zip(list1, list2): 
 List comprehension[x for x in list if condition] 
FunctionsDefine functiondef func_name(params): 
 Return valuereturn value 
 Default parameterdef func(param="default"): 
 *argsdef func(*args): 
 **kwargsdef func(**kwargs): 
 Lambdalambda x: x*2 
 Maplist(map(func, iterable)) 
 Filterlist(filter(func, iterable)) 
 Reducefrom functools import reduce 
File OperationsOpen fileopen("file.txt", "r") 
 Read filefile.read() / file.readlines() 
 Write filefile.write("text") 
 Close filefile.close() 
 Context managerwith open("file") as f: 
Exception HandlingTry-excepttry: except: 
 Specific exceptionexcept ValueError: 
 Finallyfinally: 
 Raise exceptionraise Exception("msg") 
Classes & OOPDefine classclass MyClass: 
 Constructordef __init__(self): 
 Methoddef method(self): 
 Inheritanceclass Child(Parent): 
 Super classsuper().__init__() 
 Class variableclass_var = value 
 Instance variableself.var = value 
ModulesImport moduleimport module 
 Import specificfrom module import func 
 Import with aliasimport module as alias 
 Import allfrom module import * 
String Formattingf-stringf"Value: {var}" 
 Format method"{}".format(var) 
 Percent formatting"%s" % var 
Math OperationsPower2 ** 3 
 Floor division7 // 2 
 Modulo7 % 2 
 Absolute valueabs(-5) 
 Roundround(3.14159, 2) 
 Max/Minmax([1, 2, 3]) / min([1, 2, 3]) 
 Sumsum([1, 2, 3]) 
Boolean OperationsAndcondition1 and condition2 
 Orcondition1 or condition2 
 Notnot condition 
 Comparison==, !=, >, <, >=, <= 
Type ConversionTo stringstr(123) 
 To integerint("123") 
 To floatfloat("3.14") 
 To listlist("abc") 
 To tupletuple([1, 2, 3]) 
 To setset([1, 2, 2]) 

🚀 Essential Code Snippets

1. String Manipulation

text = "  Hello, World!  "

# Remove whitespace
clean = text.strip()

# Convert to uppercase
upper = text.upper()

# Replace text
replaced = text.replace("World", "Python")

# Split into words
words = text.split(", ")

# Join list into string
joined = "-".join(["Python", "is", "awesome"])

print(clean, upper, replaced, words, joined)

2. List Comprehensions

# Basic list comprehension
squares = [x**2 for x in range(10)]

# With condition
evens = [x for x in range(20) if x % 2 == 0]

# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]

print(squares)    # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(evens)      # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print(matrix)     # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

3. Dictionary Operations

# Create dictionary
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Access values
print(person["name"])           # Alice
print(person.get("country", "USA"))  # USA (default)

# Update dictionary
person["age"] = 31
person["email"] = "alice@example.com"

# Iterate through dictionary
for key, value in person.items():
    print(f"{key}: {value}")

# Get keys and values
keys = list(person.keys())
values = list(person.values())

4. File Handling

# Reading a file
with open("input.txt", "r") as file:
    content = file.read()
    lines = file.readlines()

# Writing to a file
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

# Appending to a file
with open("log.txt", "a") as file:
    file.write(f"Log entry: {datetime.now()}\n")

# Reading CSV file
import csv
with open("data.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

5. Exception Handling

try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError as e:
    print(f"Invalid value: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
else:
    print("No exceptions occurred")
finally:
    print("This always executes")

# Raising custom exceptions
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

6. Working with Sets

# Create sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Set operations
union = set1 | set2           # {1, 2, 3, 4, 5, 6}
intersection = set1 & set2     # {3, 4}
difference = set1 - set2        # {1, 2}
symmetric_diff = set1 ^ set2    # {1, 2, 5, 6}

# Set methods
set1.add(5)
set1.remove(1)
set1.discard(10)  # No error if not exists
is_member = 3 in set1  # True

7. Lambda Functions

# Simple lambda
square = lambda x: x ** 2
print(square(5))  # 25

# Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 4))  # 7

# Lambda with conditional
is_even = lambda x: x % 2 == 0
print(is_even(4))  # True

# Using lambda with map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# Using lambda with filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

8. Class Basics

class Dog:
    # Class variable
    species = "Canis familiaris"
    
    def __init__(self, name, age):
        # Instance variables
        self.name = name
        self.age = age
    
    def bark(self):
        return f"{self.name} says Woof!"
    
    def birthday(self):
        self.age += 1
        return f"{self.name} is now {self.age} years old"

# Create instance
my_dog = Dog("Buddy", 3)
print(my_dog.bark())        # Buddy says Woof!
print(my_dog.birthday())    # Buddy is now 4 years old
print(my_dog.species)        # Canis familiaris

9. Time and Date

from datetime import datetime, timedelta

# Current date and time
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# Create specific date
date = datetime(2026, 2, 17)
print(date)

# Date arithmetic
future = now + timedelta(days=7)
past = now - timedelta(hours=24)

# Parse string to date
date_str = "2026-02-17"
parsed = datetime.strptime(date_str, "%Y-%m-%d")

# Calculate difference
diff = future - now
print(f"Days until: {diff.days}")

10. Working with JSON

import json

# Dictionary to JSON
data = {
    "name": "Python",
    "version": 3.12,
    "features": ["easy", "powerful", "versatile"]
}

# Convert to JSON string
json_string = json.dumps(data, indent=2)
print(json_string)

# Parse JSON string
parsed = json.loads(json_string)
print(parsed["features"])

# Read JSON file
with open("data.json", "r") as file:
    data = json.load(file)

# Write JSON file
with open("output.json", "w") as file:
    json.dump(data, file, indent=2)

📚 Common Import Statements

PurposeImport Statement
Math operationsimport math
Random numbersimport random
Date and timefrom datetime import datetime
Regular expressionsimport re
JSON handlingimport json
CSV filesimport csv
File pathsfrom pathlib import Path
HTTP requestsimport requests
Data analysisimport pandas as pd
Plottingimport matplotlib.pyplot as plt
NumPy arraysimport numpy as np
System operationsimport os
Command line argsimport sys
Time operationsimport time
Copy objectsimport copy
Collectionsfrom collections import defaultdict, Counter
Itertoolsfrom itertools import count, cycle

⚡ Time-Saving Tips

1. Use f-strings for formatting

# Old way
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))

# Better way
print(f"Name: {name}, Age: {age}")

2. Use enumerate for index and value

# Old way
items = ['a', 'b', 'c']
for i in range(len(items)):
    print(i, items[i])

# Better way
for i, item in enumerate(items):
    print(i, item)

3. Use zip for parallel iteration

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

4. Use context managers for files

# Old way
file = open("data.txt", "r")
content = file.read()
file.close()

# Better way
with open("data.txt", "r") as file:
    content = file.read()

5. Use list comprehensions instead of loops

# Old way
squares = []
for i in range(10):
    squares.append(i**2)

# Better way
squares = [i**2 for i in range(10)]

6. Use defaultdict for counting

from collections import defaultdict

# Old way
counts = {}
for item in items:
    if item not in counts:
        counts[item] = 0
    counts[item] += 1

# Better way
counts = defaultdict(int)
for item in items:
    counts[item] += 1

7. Use Counter for frequency analysis

from collections import Counter

words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)

print(word_counts.most_common(2))  # [('apple', 3), ('banana', 2)]

8. Use pathlib for file paths

from pathlib import Path

# Old way
import os
path = os.path.join('folder', 'file.txt')

# Better way
path = Path('folder') / 'file.txt'

# Check if exists
if path.exists():
    content = path.read_text()

🎯 Best Practices

  1. Use meaningful variable names
    # Bad
    x = 5
    y = 10
       
    # Good
    width = 5
    height = 10
    
  2. Write docstrings for functions
    def calculate_area(length, width):
        """Calculate the area of a rectangle.
           
        Args:
            length: The length of the rectangle
            width: The width of the rectangle
               
        Returns:
            The area of the rectangle
        """
        return length * width
    
  3. Use type hints (Python 3.5+)
    def greet(name: str) -> str:
        return f"Hello, {name}!"
    
  4. Handle exceptions gracefully
    try:
        result = risky_operation()
    except SpecificException as e:
        logger.error(f"Error: {e}")
        raise
    
  5. Use constants for magic numbers
    # Bad
    if temperature > 37:
        print("High temperature")
       
    # Good
    NORMAL_TEMP = 37
    if temperature > NORMAL_TEMP:
        print("High temperature")
    

📖 Common Mistakes to Avoid

  1. Modifying list while iterating
    # Bad - will cause issues
    items = [1, 2, 3, 4, 5]
    for item in items:
        if item % 2 == 0:
            items.remove(item)
       
    # Good - create new list
    items = [1, 2, 3, 4, 5]
    items = [item for item in items if item % 2 != 0]
    
  2. Using mutable default arguments
    # Bad - shared across calls
    def append_to(item, lst=[]):
        lst.append(item)
        return lst
       
    # Good - use None as default
    def append_to(item, lst=None):
        if lst is None:
            lst = []
        lst.append(item)
        return lst
    
  3. Comparing with None
    # Bad
    if x == None:
        pass
       
    # Good
    if x is None:
        pass
    
  4. Forgetting to use list() on map/filter
    # In Python 3, map returns iterator
    result = map(lambda x: x*2, [1, 2, 3])
    print(list(result))  # Need to convert to list
    

🔧 Debugging Tips

  1. Use print statements strategically
    print(f"Debug: x = {x}, y = {y}")
    
  2. Use pdb for interactive debugging
    import pdb; pdb.set_trace()
    
  3. Use type() to check variable types
    print(type(variable))
    
  4. Use dir() to explore objects
    print(dir(my_object))
    
  5. Use help() for documentation
    help(str.upper)
    

Conclusion

This Python cheatsheet covers the most essential concepts and operations you’ll use daily as a Python developer. Keep this guide bookmarked and refer to it whenever you need a quick reminder. The more you practice these patterns, the more natural they’ll become.

Remember, the best way to learn Python is by writing code. Start with small projects, experiment with these concepts, and gradually build up your skills. Happy coding!