Python Shortcuts Cheat Sheet

1. Basic Syntax

print(“Hello, World!”)      # Output text

x, y, z = 5, “Hello”, 3.14  # Multiple assignments

a, b = b, a                 # Swap values

2. Data Types & Conversions

int(“10”), float(“10.5”), str(100)  # Type conversion

list(“abc”)   # [‘a’, ‘b’, ‘c’]

set([1, 2, 2])  # {1, 2}

tuple([1, 2, 3])  # (1, 2, 3)

3. Lists, Tuples, Sets, Dictionaries

lst = [1, 2, 3] 

lst.append(4)      # Add item

lst.extend([5, 6]) # Merge lists

lst.pop(0)         # Remove first element

tup = (1, 2, 3) 

s = {1, 2, 3} 

d = {“a”: 1, “b”: 2}

d[“c”] = 3         # Add key-value pair

4. List Comprehensions

squared = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]

evens = [x for x in range(10) if x % 2 == 0]

5. Loops & Conditionals

for i in range(5): print(i) 

while x > 0: x -= 1 

if x > 5: print(“Big”) 

elif x == 5: print(“Equal”) 

else: print(“Small”)

6. Functions & Lambda Expressions

def add(a, b=5): return a + b 

print(add(3))  # 8

multiply = lambda x, y: x * y 

print(multiply(2, 3))  # 6

7. Dictionary & Set Operations

d = {“a”: 1, “b”: 2}

print(d.keys(), d.values(), d.items())

s1, s2 = {1, 2, 3}, {3, 4, 5}

print(s1 & s2)  # {3} (Intersection)

print(s1 | s2)  # {1, 2, 3, 4, 5} (Union)

8. File Handling

with open(“file.txt”, “r”) as f:

    content = f.read() 

with open(“file.txt”, “w”) as f:

    f.write(“Hello, World!”)

9. Exception Handling

try:

    x = 1 / 0

except ZeroDivisionError:

    print(“Cannot divide by zero!”)

finally:

    print(“Done”)

10. Useful Built-in Functions

sum([1, 2, 3])  # 6

len(“Python”)   # 6

max([5, 2, 9])  # 9

min([5, 2, 9])  # 2

sorted([3, 1, 2])  # [1, 2, 3]

11. Modules & Imports

import math 

print(math.sqrt(25))  # 5.0 

from random import randint

print(randint(1, 10))  # Random number 1-10

12. One-liners

[x**2 for x in range(5)]  # List comprehension

print(“Yes” if x > 0 else “No”)  # Ternary operator

13. Enumerate & Zip

lst = [“a”, “b”, “c”]

for i, v in enumerate(lst): 

    print(i, v)  # (0, ‘a’), (1, ‘b’), (2, ‘c’)

nums = [1, 2, 3]

letters = [“A”, “B”, “C”]

for n, l in zip(nums, letters):

    print(n, l)  # (1, ‘A’), (2, ‘B’), (3, ‘C’)

14. Dictionary Comprehensions

squared = {x: x*x for x in range(5)}  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

15. Sorting with Lambda

students = [(“John”, 25), (“Jane”, 22), (“Dave”, 28)]

students.sort(key=lambda x: x[1])  # Sort by age

16. Defaultdict & Counter (from collections)

from collections import defaultdict, Counter

d = defaultdict(int)

d[“a”] += 1  # d[“a”] is now 1

counter = Counter(“banana”) 

print(counter)  # {‘b’: 1, ‘a’: 3, ‘n’: 2}

17. Unpacking

a, b, *rest = [1, 2, 3, 4]

print(a, b, rest)  # 1, 2, [3, 4]

18. Filtering with filter()

nums = [1, 2, 3, 4, 5]

evens = list(filter(lambda x: x % 2 == 0, nums))  # [2, 4]

19. Map Function

squared = list(map(lambda x: x**2, [1, 2, 3]))  # [1, 4, 9]

20. Any & All

nums = [0, 1, 2, 3]

print(any(nums))  # True (at least one True)

print(all(nums))  # False (not all True)

21. Set Operations

s1, s2 = {1, 2, 3}, {3, 4, 5}

print(s1 – s2)  # {1, 2} (Difference)

print(s1 ^ s2)  # {1, 2, 4, 5} (Symmetric difference)

22. Namedtuples (from collections)

from collections import namedtuple

Person = namedtuple(“Person”, “name age”)

p = Person(name=”Alice”, age=30)

print(p.name, p.age)

23. f-Strings (String Formatting)

name = “John”

age = 25

print(f”My name is {name} and I’m {age} years old.”)

24. Merging Dictionaries

d1 = {“a”: 1, “b”: 2}

d2 = {“b”: 3, “c”: 4}

merged = {**d1, **d2}  # {‘a’: 1, ‘b’: 3, ‘c’: 4}

25. Time & Performance Tricks

from time import time

start = time()

# Your code here

end = time()

print(f”Execution time: {end – start:.5f} seconds”)

26. Using itertools for Efficient Iterations

from itertools import permutations, combinations, product, cycle

print(list(permutations([1, 2, 3])))  # All orderings

print(list(combinations([1, 2, 3], 2)))  # Unique pairs

print(list(product([1, 2], [3, 4])))  # Cartesian product

# Infinite cycle (useful for looping animations, etc.)

for i, val in zip(range(5), cycle(“AB”)):

    print(val, end=” “)  # A B A B A

27. Flattening a List of Lists

nested = [[1, 2], [3, 4], [5, 6]]

flat = [item for sublist in nested for item in sublist]

print(flat)  # [1, 2, 3, 4, 5, 6]

28. Getting the Most Frequent Item in a List

from collections import Counter

nums = [1, 2, 2, 3, 3, 3, 4]

most_common = Counter(nums).most_common(1)[0][0]

print(most_common)  # 3

29. Reversing a String/List

s = “hello”

print(s[::-1])  # “olleh”

lst = [1, 2, 3, 4]

print(lst[::-1])  # [4, 3, 2, 1]

30. One-Liner Dictionary Inversion

d = {“a”: 1, “b”: 2, “c”: 3}

inverted = {v: k for k, v in d.items()}

print(inverted)  # {1: ‘a’, 2: ‘b’, 3: ‘c’}

31. Removing Duplicates While Maintaining Order

items = [1, 2, 2, 3, 4, 3, 5]

unique = list(dict.fromkeys(items))

print(unique)  # [1, 2, 3, 4, 5]

32. Checking Memory Usage of an Object

import sys

x = [1, 2, 3]

print(sys.getsizeof(x))  # Bytes used by list

33. Using dataclasses for Clean Object Representation

from dataclasses import dataclass

@dataclass

class Person:

    name: str

    age: int

p = Person(“Alice”, 30)

print(p)  # Person(name=’Alice’, age=30)

34. Quick Debugging with pdb

import pdb; pdb.set_trace()  # Set a breakpoint

35. Convert JSON to Dictionary

import json

data = ‘{“name”: “Alice”, “age”: 30}’

parsed = json.loads(data)

print(parsed[“name”])  # Alice

36. Sorting Complex Data

students = [{“name”: “Alice”, “score”: 90}, {“name”: “Bob”, “score”: 80}]

sorted_students = sorted(students, key=lambda x: x[“score”], reverse=True)

37. try/except in One Line

try: x = 1 / 0

except ZeroDivisionError: x = None

38. functools.lru_cache for Memoization

from functools import lru_cache

@lru_cache(maxsize=100)

def fib(n):

    if n < 2: return n

    return fib(n-1) + fib(n-2)

print(fib(50))  # Much faster due to caching!

39. Parallel Processing with multiprocessing

from multiprocessing import Pool

def square(n):

    return n * n

with Pool(4) as p:

    print(p.map(square, [1, 2, 3, 4]))  # [1, 4, 9, 16]

40. Using exec to Run Python Code

code = “print(‘Hello, world!’)”

exec(code)

41. Using pathlib for File Operations

from pathlib import Path

file = Path(“example.txt”)

file.write_text(“Hello, World!”)  # Write text to a file

print(file.read_text())  # Read file contents

42. Using re for Regex Matching

import re

text = “Email: example@mail.com”

match = re.search(r”[\w\.-]+@[\w\.-]+”, text)

print(match.group())  # example@mail.com

43. Extracting Numbers from a String

import re

text = “There are 42 apples and 7 bananas.”

numbers = list(map(int, re.findall(r’\d+’, text)))

print(numbers)  # [42, 7]

44. Convert a List of Strings to Integers

numbers = [“1”, “2”, “3”]

numbers = list(map(int, numbers))

print(numbers)  # [1, 2, 3]

45. Using shutil for File Copying & Moving

import shutil

shutil.copy(“source.txt”, “destination.txt”)  # Copy file

shutil.move(“file.txt”, “new_folder/”)  # Move file

46. Run a Shell Command in Python

import subprocess

output = subprocess.run([“ls”, “-l”], capture_output=True, text=True)

print(output.stdout)

47. Using os to List Files in a Directory

import os

print(os.listdir(“.”))  # List files in current directory

48. Creating a Simple Timer with timeit

import timeit

execution_time = timeit.timeit(“sum(range(100))”, number=10000)

print(execution_time)  # Measures execution speed

49. zip to Transpose a Matrix

matrix = [[1, 2, 3], [4, 5, 6]]

transposed = list(zip(*matrix))

print(transposed)  # [(1, 4), (2, 5), (3, 6)]

50. operator for Faster Item Retrieval

from operator import itemgetter

students = [(“Alice”, 90), (“Bob”, 80), (“Charlie”, 85)]

top_student = max(students, key=itemgetter(1))

print(top_student)  # (‘Alice’, 90)

51. Using heapq for Efficient Sorting

import heapq

nums = [5, 1, 8, 3, 2]

print(heapq.nlargest(3, nums))  # [8, 5, 3]

print(heapq.nsmallest(3, nums))  # [1, 2, 3]

52. bisect for Fast Insertions in Sorted Lists

import bisect

arr = [1, 3, 4, 7]

bisect.insort(arr, 5)

print(arr)  # [1, 3, 4, 5, 7]

53. Format Large Numbers with Commas

num = 1234567890

print(f”{num:,}”)  # 1,234,567,890

54. Swap Dictionary Keys & Values

d = {“a”: 1, “b”: 2, “c”: 3}

inverted = {v: k for k, v in d.items()}

print(inverted)  # {1: ‘a’, 2: ‘b’, 3: ‘c’}

55. Chain Comparisons

x = 5

print(3 < x < 10)  # True

56. Using contextlib.suppress to Ignore Exceptions

from contextlib import suppress

with suppress(ZeroDivisionError):

    1 / 0  # No error thrown

57. Measuring Execution Time with time

import time

start = time.time()

# Some long computation

end = time.time()

print(f”Execution Time: {end – start:.5f} sec”)

58. Finding the Most Frequent Word in a Text

from collections import Counter

text = “apple orange banana apple orange apple”

words = text.split()

most_common_word = Counter(words).most_common(1)[0]

print(most_common_word)  # (‘apple’, 3)

59. Unpacking Function Arguments from a Dictionary

def greet(name, age):

    return f”Hello {name}, you are {age} years old.”

data = {“name”: “Alice”, “age”: 30}

print(greet(**data))  # Hello Alice, you are 30 years old.

60. Finding the Index of the Maximum Value in a List

numbers = [10, 20, 50, 30]

max_index = numbers.index(max(numbers))

print(max_index)  # 2

Leave a Reply

Your email address will not be published. Required fields are marked *