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).
Others
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 unchangedTruthiness:
0, "", [], {}, Noneare Falsey; most others Truthy.Identity vs Equality:
ischecks 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 2ndDict 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/**kwargsfor variable arguments.Closures: inner fn remembers outer scope; use
nonlocalto 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 viaiter(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)
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(noself),@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 = TrueType 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'refor regex;bytesvsstr(UTF-8 enc/dec).
Files & Serialization
from pathlib import Path
data = {"a":1}
Path("out.json").write_text(__import__("json").dumps(data))Prefer
jsonoverpicklefor 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_cachefor caching,itertoolsfor efficient loops.collections:Counter,defaultdict,deque,namedtuple.sorted(iterable, key=..., reverse=...)vslist.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) == 5Modules, Packages, Imports
Module = file; Package = folder with
__init__.py.Entry point guard:
if __name__ == "__main__":
main()Virtual envs:
python -m venv .venv; deps viapip/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/fractionsfor precise arithmetic.Security: never
eval/execuntrusted input; usesecretsfor 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.
def
Got it ✅ Here’s your one-liner definitions with a small, simple example for each — following the style you liked earlier:
Built-in Function – A function provided by Python itself, available without importing anything. Example:
len("AWS")→ returns3.Library / Module – A collection of Python code (functions, classes, variables) that can be imported and reused. Example:
import boto3→boto3is a library,boto3.sessionis a module.Object – An instance of a class that contains data (attributes) and functionality (methods). Example:
ec2 = boto3.client("ec2")→ec2is an object.Method – A function that belongs to an object and can access/modify its data. Example:
ec2.describe_instances()→describe_instancesis a method.Class – A blueprint for creating objects with attributes and methods. Example:
class S3Bucket: passAttribute – A variable that belongs to an object or class. Example:
bucket.namewherenameis an attribute.Parameter – A variable in a function/method definition that accepts input. Example:
def upload(file_name)→file_nameis a parameter.Argument – The actual value passed to a parameter when calling a function. Example:
upload("data.csv")→"data.csv"is an argument.Decorator – A function that modifies the behavior of another function or method. Example:
@log_time def create_ec2(): passList – An ordered, mutable collection of items. Example:
regions = ["us-east-1", "us-west-2"]List Manipulation – Changing list content by adding, removing, or updating elements. Example:
regions.append("ap-south-1")List Comprehension – A concise way to create lists using a single line of code. Example:
[r.upper() for r in regions]Dictionary – A collection of key-value pairs, unordered and mutable. Example:
ec2_tags = {"Name": "ProdServer", "Env": "Prod"}Tuple – An ordered, immutable collection of items. Example:
aws_services = ("EC2", "S3", "Lambda")Set – An unordered collection of unique items. Example:
aws_regions = {"us-east-1", "us-west-2"}Variable – A name that stores data in memory. Example:
region = "us-east-1"Loop – A control structure to repeat code multiple times. Example:
for r in regions: print(r)Conditional Statement – Executes code only if a condition is met. Example:
if region == "us-east-1": print("N. Virginia")Exception Handling – Managing errors without crashing the program. Example:
try: 1/0 except ZeroDivisionError: print("Error")Lambda Function – A small, anonymous function. Example:
square = lambda x: x**2Generator – A function that yields values one at a time using
yield. Example:def aws_zones(): yield "us-east-1a" yield "us-east-1b"Import – Bringing code from another file or library into your program. Example:
from boto3 import clientPackage – A directory containing multiple Python modules with an
__init__.pyfile. Example:boto3is a package containing many modules likeboto3.ec2.Namespace – A container that holds names (variables, functions, classes) to avoid conflicts. Example:
math.sqrt→sqrtis insidemathnamespace.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