Basics

len() is a built-in function

ec2 → is a client object created from the boto3 library.

ec2.describe_instances() → describe_instances() → is a method that belongs to that ec2 object.

() after a function or method contains parameters (also called arguments when you pass values into them).

chevron-rightOthershashtag

Awesome—building on what you already locked down (built-ins, methods, libraries, objects, parameters/arguments), here’s a compact Python interview cheat-sheet with the rest of the concepts people expect. Each item has a tiny example so it sticks.


Syntax & Types

  • Mutable vs Immutable: lists/dicts/sets are mutable; str/int/tuple are immutable.

    s = "hi"; s.replace("h", "H")   # returns new string, s unchanged
  • Truthiness: 0, "", [], {}, None are Falsey; most others Truthy.

  • Identity vs Equality: is checks identity, == checks value.

Collections & Manipulation

  • List ops: append, extend, insert, pop, remove, clear, sort, reverse.

    a = [3,1,2]; a.sort()           # [1,2,3]
  • Slicing: seq[start:stop:step]; copies are shallow.

    a[::2]      # every 2nd
  • Dict ops: get, setdefault, update, views (keys, items, values).

  • Set ops: union |, intersection &, difference -, symmetric ^.

  • Shallow vs Deep copy:

    import copy
    copy.copy(obj); copy.deepcopy(obj)

Functions (first-class)

  • Default arg pitfall (don’t use mutable defaults):

    def f(x, bag=None): bag = bag or []; bag.append(x); return bag
  • *args / **kwargs for variable arguments.

  • Closures: inner fn remembers outer scope; use nonlocal to rebind.

  • Higher-order: pass/return functions (map, filter, custom).

Decorators (function & class wrappers)

import time, functools
def timed(fn):
    @functools.wraps(fn)
    def wrapper(*a, **k):
        t = time.time(); r = fn(*a, **k)
        print(f"{fn.__name__} took {time.time()-t:.3f}s"); return r
    return wrapper

@timed
def work(): return sum(range(1_000_000))
  • With params: a decorator factory that returns a decorator.

Comprehensions

[x*x for x in range(5)]                      # list
{x:x*x for x in range(3)}                    # dict
{x for x in "abracadabra"}                   # set
(x*x for x in range(10))                     # generator (lazy)
# with condition / nested:
[(i,j) for i in range(3) for j in range(3) if i!=j]

Iterables, Iterators, Generators

  • Iterable: can be looped (for x in obj).

  • Iterator: has __next__(). Create via iter(iterable).

  • Generators: functions with yield (lazy).

    def chunks(it, n):
        buf=[]; 
        for x in it:
            buf.append(x)
            if len(buf)==n: yield buf; buf=[]
        if buf: yield buf

Context Managers (with)

  • Ensure cleanup on exit.

from contextlib import contextmanager
@contextmanager
def opened(path):
    f = open(path); 
    try: yield f
    finally: f.close()

with opened("log.txt") as f: f.write("ok")

Exceptions

try:
    1/0
except ZeroDivisionError as e:
    print(e)
else:
    print("no errors")
finally:
    print("always")
# raise CustomError("msg")

OOP Essentials

class Box:
    def __init__(self, w): self._w = w
    @property
    def weight(self): return self._w      # getter
    @weight.setter
    def weight(self, v): self._w = max(0,v)

class A: pass
class B(A): pass                           # inheritance
  • @staticmethod (no self), @classmethod (cls), MRO (method resolution order), super().

  • Dunder methods: __repr__, __str__, __len__, __iter__, __getitem__, __eq__, __hash__, __enter__/__exit__, __call__.

Dataclasses

from dataclasses import dataclass
@dataclass
class User: name: str; active: bool = True

Type Hints (PEP 484)

from typing import Iterable, Optional, Protocol

def total(xs: Iterable[int]) -> int: ...
def maybe(x: Optional[int]) -> int: return x or 0

class Runner(Protocol):
    def run(self) -> None: ...

Pattern Matching (PEP 634)

def http_status(code):
    match code:
        case 200: return "OK"
        case c if 400 <= c < 500: return "Client error"
        case _: return "Other"

Strings & Formatting

name = "Pavan"; f"Hello {name.upper()} {3+2}"
"{:,.2f}".format(12345.678)   # '12,345.68'
  • re for regex; bytes vs str (UTF-8 enc/dec).

Files & Serialization

from pathlib import Path
data = {"a":1}
Path("out.json").write_text(__import__("json").dumps(data))
  • Prefer json over pickle for interoperability/safety.

Concurrency

  • GIL: only one Python bytecode thread runs at a time in CPython.

  • Threading: good for I/O. Multiprocessing: CPU-bound.

  • Asyncio: cooperative concurrency for I/O.

import asyncio, aiohttp
async def fetch(url):
    async with aiohttp.ClientSession() as s:
        async with s.get(url) as r: return await r.text()
asyncio.run(fetch("https://example.com"))

Performance & Utilities

  • functools.lru_cache for caching, itertools for efficient loops.

  • collections: Counter, defaultdict, deque, namedtuple.

  • sorted(iterable, key=..., reverse=...) vs list.sort() (in-place).

  • Profile: timeit, cProfile.

Testing

  • pytest/unittest, mocking with unittest.mock.

def add(a,b): return a+b
def test_add(): assert add(2,3) == 5

Modules, Packages, Imports

  • Module = file; Package = folder with __init__.py.

  • Entry point guard:

if __name__ == "__main__":
    main()
  • Virtual envs: python -m venv .venv; deps via pip / requirements.txt.

CLI & OS

import argparse, os, subprocess
p = argparse.ArgumentParser(); p.add_argument("--name"); args = p.parse_args()
os.getenv("HOME")
subprocess.run(["echo","hi"], check=True)

Modern Extras

  • Walrus operator := (assignment expression).

  • Extended unpacking: a, *mid, b = seq.

  • dataclass(frozen=True) for immutability.

  • contextlib.suppress(KeyError) to ignore specific exceptions.

  • decimal/fractions for precise arithmetic.

  • Security: never eval/exec untrusted input; use secrets for tokens.


If you’d like, I can turn this into a one-page printable PDF cheat-sheet with side-by-side examples (decorators, comprehensions, generators, context managers, OOP) so you can cram before your interview.

chevron-rightdefhashtag

Got it ✅ Here’s your one-liner definitions with a small, simple example for each — following the style you liked earlier:


  1. Built-in Function – A function provided by Python itself, available without importing anything. Example: len("AWS") → returns 3.

  2. Library / Module – A collection of Python code (functions, classes, variables) that can be imported and reused. Example: import boto3boto3 is a library, boto3.session is a module.

  3. Object – An instance of a class that contains data (attributes) and functionality (methods). Example: ec2 = boto3.client("ec2")ec2 is an object.

  4. Method – A function that belongs to an object and can access/modify its data. Example: ec2.describe_instances()describe_instances is a method.

  5. Class – A blueprint for creating objects with attributes and methods. Example:

    class S3Bucket:
        pass
  6. Attribute – A variable that belongs to an object or class. Example: bucket.name where name is an attribute.

  7. Parameter – A variable in a function/method definition that accepts input. Example: def upload(file_name)file_name is a parameter.

  8. Argument – The actual value passed to a parameter when calling a function. Example: upload("data.csv")"data.csv" is an argument.

  9. Decorator – A function that modifies the behavior of another function or method. Example:

    @log_time
    def create_ec2():
        pass
  10. List – An ordered, mutable collection of items. Example: regions = ["us-east-1", "us-west-2"]

  11. List Manipulation – Changing list content by adding, removing, or updating elements. Example: regions.append("ap-south-1")

  12. List Comprehension – A concise way to create lists using a single line of code. Example: [r.upper() for r in regions]

  13. Dictionary – A collection of key-value pairs, unordered and mutable. Example: ec2_tags = {"Name": "ProdServer", "Env": "Prod"}

  14. Tuple – An ordered, immutable collection of items. Example: aws_services = ("EC2", "S3", "Lambda")

  15. Set – An unordered collection of unique items. Example: aws_regions = {"us-east-1", "us-west-2"}

  16. Variable – A name that stores data in memory. Example: region = "us-east-1"

  17. Loop – A control structure to repeat code multiple times. Example:

    for r in regions:
        print(r)
  18. Conditional Statement – Executes code only if a condition is met. Example:

    if region == "us-east-1":
        print("N. Virginia")
  19. Exception Handling – Managing errors without crashing the program. Example:

    try:
        1/0
    except ZeroDivisionError:
        print("Error")
  20. Lambda Function – A small, anonymous function. Example: square = lambda x: x**2

  21. Generator – A function that yields values one at a time using yield. Example:

    def aws_zones():
        yield "us-east-1a"
        yield "us-east-1b"
  22. Import – Bringing code from another file or library into your program. Example: from boto3 import client

  23. Package – A directory containing multiple Python modules with an __init__.py file. Example: boto3 is a package containing many modules like boto3.ec2.

  24. Namespace – A container that holds names (variables, functions, classes) to avoid conflicts. Example: math.sqrtsqrt is inside math namespace.

  25. Scope – The region in code where a variable is accessible. Example: A variable inside a function is not accessible outside it.


If you want, I can make this into a beautiful printable Python cheat sheet so you can keep it for quick reference. Do you want me to prepare that?

Last updated