# π Python β Complete Topics Reference
Start se end tak β ekdum kuch nahi chhodha. Ye hai tera Python ka Poora Brahmand.
# π¦ SECTION 1 β Python Fundamentals
# 1.1 Introduction
- What is Python?
- History (Guido van Rossum, 1991)
- Python 2 vs Python 3 (always use 3.x)
- CPython, PyPy, Jython, IronPython (interpreters)
- How Python runs (Interpreter, Bytecode,
.pyc) - REPL (Interactive Shell)
- Installing Python & pip
- Virtual Environments (
venv,virtualenv,conda) - Running scripts:
python script.py __name__ == "__main__"idiom- PEP 8 β Style Guide (must follow!)
- PEP 20 β The Zen of Python (
import this)
# 1.2 Variables & Data Types
- Variables (dynamic typing)
type()functionid()function (memory address)- Primitive Types:
int(arbitrary precision!)float(IEEE 754)complex(3 + 4j)bool(True,False) β subclass of int!strNoneType(None)
- Collection Types:
listtupledictsetfrozensetbytes,bytearray,memoryview
- Type Conversion (implicit vs explicit)
int(),float(),str(),bool(),list(),tuple(),set(),dict()isinstance(),issubclass()
# 1.3 Operators
- Arithmetic:
+,-,*,/,//(floor div),%,** - Comparison:
==,!=,<,>,<=,>= - Logical:
and,or,not - Bitwise:
&,|,^,~,<<,>> - Assignment:
=,+=,-=,*=,/=,//=,%=,**=,&=,|=,^= - Identity:
is,is not - Membership:
in,not in - Walrus Operator (
:=) β Python 3.8+ - Operator Precedence
# π SECTION 2 β Control Flow
# 2.1 Conditionals
if,elif,else- Nested conditionals
- Truthy & Falsy values in Python
- One-liner ternary:
x if condition else y matchstatement (Python 3.10+) β structural pattern matching
# 2.2 Loops
forloop (over any iterable)whileloopbreak,continue,passelseclause on loops (unique to Python!)range()βstart,stop,step- Nested loops
enumerate()βzip()βzip_longest()
# π§© SECTION 3 β Functions
# 3.1 Basics
defkeyword- Return values (
return) Noneas default return- Docstrings (
"""...""") - Default Arguments
- Keyword Arguments
- Positional-only params (
/) - Keyword-only params (
*) *args(variable positional)**kwargs(variable keyword)- Argument order:
pos / normal * keyword_only **kwargs
# 3.2 Advanced Functions
- First-class functions
- Higher-order functions
- Lambda functions (
lambda x: x*2) - Closures β
- Nested functions
- Nonlocal & global keywords
- Recursion + base case
- Memoization (
functools.lru_cache,functools.cache) functools.partialfunctools.reduce- Function annotations (type hints)
__doc__,__name__,__annotations__functools.wraps(decorator best practice)
# 3.3 Built-in Functions (must know all!)
abs, all, any, bin, bool, breakpoint, bytearray, bytes, callable,chr, classmethod, compile, complex, delattr, dict, dir, divmod,enumerate, eval, exec, filter, float, format, frozenset, getattr,globals, hasattr, hash, help, hex, id, input, int, isinstance,issubclass, iter, len, list, locals, map, max, memoryview, min,next, object, oct, open, ord, pow, print, property, range,repr, reversed, round, set, setattr, slice, sorted, staticmethod,str, sum, super, tuple, type, vars, zip, __import__
# π‘ SECTION 4 β Strings
- String creation (single, double, triple quotes)
- Raw strings (
r"...") - Byte strings (
b"...") - f-strings (Python 3.6+) β β
f"{name!r:.2f}" - f-string = expression support (3.8+
f"{x=}") format()method & format spec%formatting (old style)- String immutability
- String indexing & slicing
[start:stop:step] - Methods:
upper,lower,title,capitalize,swapcase,strip,lstrip,rstrip,split,rsplit,splitlines,join,replace,find,rfind,index,rindex,count,startswith,endswith,isalpha,isdigit,isalnum,isspace,isupper,islower,zfill,center,ljust,rjust,encode,decode,maketrans,translate,expandtabs str.format_map()- Multiline strings
- String interning
textwrapmodulestringmodule constants
# π SECTION 5 β Lists
- Creating lists
- Indexing & Slicing
- Negative indexing
- List mutability
- Methods:
append,extend,insert,remove,pop,clear,index,count,sort,reverse,copy sorted()vs.sort()(key difference!)list.sort(key=..., reverse=True)- List Comprehension β
[expr for x in iterable if cond] - Nested list comprehensions
*unpacking- Shallow vs Deep copy (
copy.copyvscopy.deepcopy) - List as stack, list as queue (use
dequefor queue!) delstatement
# π¦ SECTION 6 β Tuples
- Creating tuples (immutability)
- Single-element tuple:
(x,) - Packing & Unpacking
- Extended unpacking (
a, *b, c = ...) - Named Tuples (
collections.namedtuple) β tuplevslistβ when to use which- Tuple as dict keys (hashable)
# ποΈ SECTION 7 β Dictionaries
- Creating dicts (
{},dict()) - Accessing, updating, deleting keys
KeyErrorhandling- Methods:
get,keys,values,items,update,pop,popitem,clear,copy,setdefault,fromkeys - Dictionary Comprehension β
{k: v for k, v in ...} - Merging dicts (
|operator, Python 3.9+) **unpacking in dicts- Ordered dicts (Python 3.7+ dicts are insertion-ordered)
collections.OrderedDictcollections.defaultdictβcollections.Counterβcollections.ChainMap- Nested dicts
- Dict as switch/case replacement
# π― SECTION 8 β Sets
- Creating sets (
{}vsset()) - Set uniqueness (no duplicates)
- Methods:
add,remove,discard,pop,clear,copy,union,intersection,difference,symmetric_difference,issubset,issuperset,isdisjoint - Set operators:
|,&,-,^ - Set Comprehension
{expr for x in iterable} frozenset(immutable, hashable set)- Set for O(1) lookups β
# ποΈ SECTION 9 β OOP (Object-Oriented Programming) β
# 9.1 Classes & Objects
classkeyword__init__constructorselfparameter- Instance variables vs Class variables
- Instance methods, Class methods (
@classmethod), Static methods (@staticmethod) clsvsself
# 9.2 Principles
- Encapsulation β private (
__x), protected (_x) - Inheritance β
class Child(Parent): - Polymorphism β method overriding
- Abstraction β
abc.ABC,@abstractmethod
# 9.3 Advanced OOP
- Multiple Inheritance
- MRO (Method Resolution Order) β C3 Linearization β
super()βisinstance(),issubclass()- Operator Overloading (Dunder/Magic methods)
__str__vs__repr____len__,__getitem__,__setitem__,__delitem____iter__,__next____contains__(inoperator)__call__(callable objects)__enter__,__exit__(context managers)__eq__,__lt__,__le__,__gt__,__ge__,__hash____add__,__mul__,__sub__,__truediv__, etc.__new__vs__init____del__(destructor)__slots__(memory optimization)__class__,__dict__,__doc__@property,@x.setter,@x.deleterβdataclasses.dataclass(Python 3.7+) βdataclasses.field
# 9.4 Metaclasses
- What is a metaclass?
typeas metaclass- Custom metaclasses
__new__in metaclass- Use cases: singleton, ORM, registration
# π SECTION 10 β Decorators β
- What are decorators?
- Function decorators
- Class decorators
@wrapsfrom functools- Decorators with arguments
- Stacking decorators
- Built-in decorators:
@property,@classmethod,@staticmethod,@abstractmethod,@dataclass - Practical use cases: logging, timing, retry, auth, caching
# βοΈ SECTION 11 β Iterators & Generators β
- Iterable vs Iterator protocol
iter(),next()StopIterationexception- Custom Iterators (implementing
__iter__+__next__) - Generator Functions (
yield) β - Generator Expressions
(x for x in ...) yield from(Python 3.3+)send()to generatorsthrow(),close()on generators- Lazy evaluation benefits
- Infinite generators
itertoolsmodule ββ
# π§ SECTION 12 β Context Managers
withstatement__enter__&__exit__protocol- Exception handling inside context managers
contextlib.contextmanagerdecorator βcontextlib.suppresscontextlib.redirect_stdoutcontextlib.ExitStack- Use cases: file handling, locks, DB connections
# β οΈ SECTION 13 β Exception Handling
try,except,else,finally- Catching specific exceptions
- Catching multiple exceptions
ExceptionhierarchyBaseExceptionvsException- Built-in Exceptions:
ValueError,TypeError,KeyError,IndexError,AttributeError,NameError,ImportError,ModuleNotFoundError,OSError,IOError,FileNotFoundError,PermissionError,RuntimeError,StopIteration,GeneratorExit,ArithmeticError,ZeroDivisionError,OverflowError,MemoryError,RecursionError,NotImplementedError,AssertionError,SystemExit,KeyboardInterrupt raisestatementraise ... from ...(exception chaining)- Custom exceptions (subclassing
Exception) assertstatementwarningsmoduletracebackmodulesys.exc_info()
# π SECTION 14 β File Handling & I/O
open()β modes:r,w,a,rb,wb,r+,xread(),readline(),readlines()write(),writelines()seek(),tell()with open(...) as f:β (always use this!)- File encoding (
encoding="utf-8") os.pathmodulepathlib.Pathβ (modern way!)shutilβ copy, move, deletetempfileβ temporary filesglobβ file pattern matching- CSV:
csv.reader,csv.writer,csv.DictReader,csv.DictWriter - JSON:
json.load,json.dump,json.loads,json.dumps pickleβ serialization (binary)shelveconfigparserio.StringIO,io.BytesIO
# π’ SECTION 15 β Numbers & Math
- Integer arithmetic (arbitrary precision)
- Float precision issues
decimal.Decimal(exact decimal math) βfractions.Fractioncomplexnumbersmathmodule:floor,ceil,sqrt,log,log2,log10,exp,pow,factorial,gcd,lcm,sin,cos,tan,pi,e,inf,nan,isnan,isinf,isfinite,comb,perm,prodstatisticsmodule:mean,median,mode,stdev,variance,quantilesrandommodule:random,randint,choice,choices,shuffle,sample,seed,uniform,gausssecretsmodule (cryptographically secure random)- Number bases:
bin(),oct(),hex(),int(x, base) - Bitwise tricks
# π SECTION 16 β Date & Time
datetimemodule:date,time,datetime,timedelta,timezonedatetime.now(),datetime.utcnow()- Formatting:
strftime(),strptime() timedeltaarithmetic- Timezone handling:
pytz,zoneinfo(Python 3.9+) timemodule:time(),sleep(),perf_counter(),process_time()calendarmoduledateutillibrary (third-party, very useful)
# π¬ SECTION 17 β Comprehensions (All types)
- List Comprehension:
[expr for x in iter if cond] - Dict Comprehension:
{k: v for k, v in iter} - Set Comprehension:
{expr for x in iter} - Generator Expression:
(expr for x in iter) - Nested comprehensions
- Multiple
forclauses - Conditional expressions inside comprehensions
- Performance: comprehension vs loop
# π§° SECTION 18 β Standard Library (Must-know modules)
# Data Structures
collections:deque,Counter,defaultdict,OrderedDict,namedtuple,ChainMap,UserDict,UserListheapq: min-heap operations,heappush,heappop,heapify,nlargest,nsmallestbisect: binary search on sorted lists,bisect_left,bisect_right,insortarray: typed arrays
# Functional
functools:reduce,partial,lru_cache,cache,wraps,total_ordering,singledispatchitertoolsββ:count,cycle,repeat,chain,islice,zip_longest,product,permutations,combinations,combinations_with_replacement,groupby,starmap,takewhile,dropwhile,filterfalse,accumulate,tee,compress,pairwiseoperator:itemgetter,attrgetter,methodcaller
# OS & System
os:getcwd,chdir,listdir,mkdir,makedirs,remove,rmdir,rename,environ,getenv,path,walk,statsys:argv,path,exit,stdin,stdout,stderr,version,platform,modules,getrecursionlimit,setrecursionlimitsubprocess:run,Popen,call,check_outputplatformsignalshutilpathlib
# Text & String
re(Regular Expressions) βstringtextwrapdifflibunicodedata
# Networking & Web
http.client,http.serverurllib:urllib.request,urllib.parse,urllib.errorsocketsslemail,smtplib,imaplibhtml,html.parserxml.etree.ElementTree
# Concurrency
threadingmultiprocessingasyncioβconcurrent.futuresqueue
# Other Important
abc(Abstract Base Classes)copypprintreprlibenumdataclassestypingcontextlibwarningsloggingunittestargparseconfigparserhashlibhmacsecretsuuidstructioinspectdisasttokenizegc(garbage collector)weakreftracemalloc
# π SECTION 19 β Regular Expressions (`re` module)
re.match(),re.search(),re.findall(),re.finditer()re.sub(),re.subn()re.split()re.compile()β compiled patterns- Flags:
re.IGNORECASE,re.MULTILINE,re.DOTALL,re.VERBOSE,re.ASCII - Patterns:
.,^,$,*,+,?,{n,m},[],[^],\d,\D,\w,\W,\s,\S,\b,\B - Groups:
(),(?:...),(?P<name>...),(?P=name) - Lookahead:
(?=...),(?!...) - Lookbehind:
(?<=...),(?<!...) Matchobject methods:group(),groups(),groupdict(),start(),end(),span()- Greedy vs Non-greedy (
*?,+?,??) - Raw strings with regex
# β‘ SECTION 20 β Async Python β
# 20.1 Concurrency Concepts
- Concurrency vs Parallelism
- I/O-bound vs CPU-bound tasks
- GIL (Global Interpreter Lock) β what it is, impact
- Threading for I/O-bound
- Multiprocessing for CPU-bound
- Asyncio for I/O-bound (single-threaded!)
# 20.2 `asyncio`
async defβ coroutinesawaitkeywordasyncio.run()asyncio.create_task()asyncio.gather()βasyncio.wait()asyncio.wait_for()(timeout)asyncio.sleep()asyncio.Queueasyncio.Event,asyncio.Lock,asyncio.Semaphore- Event Loop:
asyncio.get_event_loop() async for(async iterators)async with(async context managers)__aiter__,__anext__,__aenter__,__aexit__- Async generators
asyncio.shield()asyncio.timeout()(Python 3.11+)- Task cancellation
- Exception handling in tasks
# 20.3 Threading
threading.Threaddaemonthreadsthreading.Lock,RLock,Semaphore,Event,Condition,Barrier- Thread-local data (
threading.local) threading.Timerconcurrent.futures.ThreadPoolExecutorβ
# 20.4 Multiprocessing
multiprocessing.Processmultiprocessing.Poolβ βmap,starmap,apply_asyncmultiprocessing.Queue,Pipemultiprocessing.Value,Array(shared memory)multiprocessing.Managerconcurrent.futures.ProcessPoolExecutorβmultiprocessing.shared_memory(Python 3.8+)
# π SECTION 21 β Type Hints & Typing Module (Python 3.5+)
- Why type hints?
- Basic annotations:
int,str,float,bool,None List,Dict,Tuple,Set,Optional,Union- Python 3.9+ built-in generics:
list[int],dict[str, int] Optional[X]=X | None(Python 3.10+)Union[X, Y]=X | Y(Python 3.10+)AnyCallableTypeVar(generics)GenericclassProtocol(structural subtyping) βTypedDictLiteralFinalClassVarAnnotatedoverloadTYPE_CHECKINGcast()ParamSpec,ConcatenateTypeAlias(Python 3.10+)TypeGuardSelftype (Python 3.11+)Never,NoReturn- Static type checkers:
mypy,pyright,pytype
# π§ SECTION 22 β Functional Programming in Python
- Pure functions
- Immutability
map(),filter(),zip(),enumerate()functools.reduce()- Lambda functions
- Closures
- Currying (
functools.partial) - Function composition
functools.singledispatch(generic functions)- Monads (basic concept)
- Lazy evaluation with generators
# π§ͺ SECTION 23 β Testing
unittestβ built-in test frameworkTestCase,setUp,tearDown,setUpClass,tearDownClass- Assertions:
assertEqual,assertNotEqual,assertTrue,assertFalse,assertRaises,assertIn,assertIsNone,assertAlmostEqual - Test Discovery
unittest.mock:Mock,MagicMock,patch,call
pytestββ (industry standard)- Fixtures (
@pytest.fixture) - Parametrize (
@pytest.mark.parametrize) conftest.pypytest.raises- Plugins:
pytest-cov,pytest-asyncio,pytest-mock - Markers
- Fixtures (
doctestβ tests in docstrings- TDD (Test Driven Development)
- Code Coverage:
coverage.py - Property-based testing:
hypothesis
# π SECTION 24 β Modules & Packages
importstatementfrom ... import ...import ... as ...__init__.py- Relative imports (
.,..) __all__variable- Module
__name__,__file__,__package__ - Package structure
- Namespace packages (PEP 420)
importlibpkgutilsys.pathmanipulation- Circular imports (problem & solution)
- Lazy imports
importlib.reload()
# π‘ SECTION 25 β Networking & Web
socketprogramming (TCP, UDP)http.server(simple server)urllib(basic requests)requestslibrary β (industry standard)- GET, POST, PUT, DELETE
- Sessions, cookies, headers
- Timeouts, retries
- Authentication
- File upload
httpx(async support, modern)aiohttp(async HTTP)- WebSockets:
websocketslibrary - REST API consumption
jsonparsing
# π SECTION 26 β Web Frameworks (Overview)
Flaskβ micro framework- Routes, views, templates (Jinja2)
- Request/Response
- Blueprints
- Extensions: Flask-SQLAlchemy, Flask-Login
Djangoβ batteries included- MTV (Model-Template-View)
- ORM, Admin, Auth, Forms, Migrations
settings.py,urls.py,views.py,models.py
FastAPIβ (modern, async, automatic docs)- Path params, query params, body
- Pydantic models
- Dependency injection
- OpenAPI/Swagger auto-docs
asyncfirst
Starlette(ASGI framework, FastAPI is built on it)- WSGI vs ASGI
# ποΈ SECTION 27 β Databases & ORM
- Raw SQL with
sqlite3(built-in) psycopg2(PostgreSQL)pymysql/mysql-connector(MySQL)SQLAlchemyβ (industry ORM)- Core vs ORM
- Models, Sessions, Queries
- Relationships, Joins
- Migrations with
Alembic
Tortoise ORM(async ORM)Peewee(lightweight ORM)- NoSQL:
pymongo(MongoDB) - Redis:
redis-py databaseslibrary (async queries)
# π SECTION 28 β Data Science Stack (Overview)
NumPyβ β N-dimensional arrays, vectorization, broadcastingPandasβ β DataFrame, Series, data manipulationMatplotlibβ 2D plottingSeabornβ statistical visualizationPlotlyβ interactive chartsSciPyβ scientific computingScikit-learnβ Machine LearningJupyter Notebook / JupyterLabPolars(modern, fast DataFrame library)
# π€ SECTION 29 β Machine Learning & AI (Python's Domain)
scikit-learnβ classification, regression, clustering, preprocessing, pipelines- Deep Learning:
TensorFlow/KerasPyTorchβ (industry favorite for research)
transformers(HuggingFace) β NLP, LLMsLangChain,LlamaIndexβ LLM appsOpenAIPython SDKAnthropicPython SDK πopencv-pythonβ Computer VisionNLTK,spaCyβ NLP
# π οΈ SECTION 30 β Packaging & Distribution
setup.py(old way)pyproject.tomlβ (modern way β PEP 517/518)setuptools,poetry,hatch,flitpipβ install, uninstall, upgrade, freeze, install -rrequirements.txt- Virtual environments:
venv,virtualenv,conda pipenvpoetryβ (dependency management + packaging)uvβ (blazing fast, modern β 2024)- Uploading to PyPI:
twine __version__- Entry points & scripts
- Building:
python -m build
# π SECTION 31 β Security
secretsmodule (secure random)hashlib(SHA256, MD5, etc.)hmacsslcryptographylibrarybcrypt,argon2(password hashing)- SQL Injection prevention (parameterized queries)
- Input validation
bandit(security linter for Python).envfiles &python-dotenvβ (never hardcode credentials!)
# β‘ SECTION 32 β Performance & Optimization
- Profiling:
cProfile,profile,pstats timeitmodule βline_profilermemory_profiler- Optimization techniques:
- Avoid global variables
- Use local variables inside loops
- List comprehensions over loops
- Generators for large data
__slots__in classesnumpyvectorization instead of loops- Caching:
functools.lru_cache - Lazy imports
- Fast alternatives:
PyPy(JIT compiled Python)Cython(Python β C)Numba(JIT for numerical code)ctypes,cffi(C extensions)mypyc
- GIL workarounds
multiprocessingfor CPU-boundasynciofor I/O-bound
# π SECTION 33 β Introspection & Metaprogramming
dir(),vars(),type(),id()inspectmodule β βsignature,getsource,isfunction,isclass,ismethod,getmembers,stackgetattr,setattr,hasattr,delattr__dict__,__class__,__bases__,__mro____getattr__,__getattribute__,__setattr__,__delattr__- Descriptors (
__get__,__set__,__delete__,__set_name__) - Metaclasses deep dive
type()to create classes dynamically- Class decorators
__init_subclass__abc.ABCMeta__slots__astmodule (Abstract Syntax Tree)dismodule (bytecode disassembly)- Code objects
exec(),eval(),compile()β and why to avoid them
# π§΅ SECTION 34 β Design Patterns in Python
- Creational: Singleton, Factory, Abstract Factory, Builder, Prototype, Borg
- Structural: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy
- Behavioral: Chain of Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor
- Pythonic patterns: Context Manager, Descriptor, Generator-as-coroutine, Mixin
# π§Ή SECTION 35 β Code Quality & Best Practices
- PEP 8 compliance
- Linters:
flake8,pylint,ruffβ (fastest, modern) - Formatters:
blackβ,autopep8,isort - Type checkers:
mypy,pyrightβ - Security:
bandit - Pre-commit hooks:
pre-commit - Docstrings: Google style, NumPy style, Sphinx style
sphinxβ documentation generation- Clean code principles in Python
- SOLID principles (Python examples)
- DRY, KISS, YAGNI
# π SECTION 36 β Logging
loggingmodule β- Log levels:
DEBUG,INFO,WARNING,ERROR,CRITICAL basicConfig()Logger,Handler,Formatter,Filter- File handlers, rotating handlers
logging.config.dictConfig()- Structured logging:
structlog loguru(modern, developer-friendly) β
# π§ SECTION 37 β CLI Tools & Scripting
sys.argvargparseβ βadd_argument,parse_args, subcommandsgetoptclickβ (best CLI library)typerβ (click + type hints, modern)richβ beautiful terminal output βcoloramaβ colored outputtqdmβ progress bars- Shell scripting with Python (
subprocess,os) invokeβ task runner
# π SECTION 38 β Environment & Config Management
- Environment variables (
os.environ,os.getenv) python-dotenvβ β.envfilesconfigparserβ.inifilespydantic-settingsβ type-safe config βdynaconfTOMLconfig (tomllibbuilt-in Python 3.11+)- 12-Factor App principles for Python
# π Extra Gyan By Your Bhai π§
Bhai sun, Python bohot bada hai β isko sab ek saath mat sikho. Ek proven roadmap deta hoon:
# πΊοΈ Learning Roadmap
Phase 1 β Core Python (4-6 weeks)
Section 1, 2, 3, 4, 5, 6, 7, 8, 13, 14
Phase 2 β Intermediate (3-4 weeks)
Section 9 (OOP β), 10 (Decorators), 11 (Generators), 12 (Context Managers), 17 (Comprehensions), 18 (Stdlib)
Phase 3 β Advanced Python (3-4 weeks)
Section 19 (Regex), 20 (Async β), 21 (Type Hints), 24 (Modules), 32 (Performance), 33 (Metaprogramming)
Phase 4 β Ecosystem (pick your path)
Web Dev β Section 25, 26, 27
Data Science β Section 28, 29
DevOps/Scripting β Section 37, 38
Phase 5 β Professional (always ongoing)
Section 22, 23 (Testing β), 30 (Packaging), 31 (Security), 34 (Design Patterns), 35 (Code Quality), 36 (Logging)
# β οΈ Top Mistakes Python Beginners Make
| Mistake | Reality |
|---|---|
Mutable default arguments def f(x=[]) |
Biggest Python gotcha! |
== se None check karna |
Always use is None |
Bare except: |
Always catch specific exceptions |
import * use karna |
Never do this in production |
+ se string concatenation in loop |
Use "".join() instead |
| Not using virtual environments | Always use venv/poetry |
time.sleep() in async code |
Use asyncio.sleep() |
Using pickle for untrusted data |
Security risk! |
# π₯ Python-Specific Power Features
Ye sab sikhle toh real Pythonista ban jaoge:
itertoolsβ underrated gem, master thiscollectionsmodule β use karo!Counter,defaultdict,deque- Generator expressions for memory efficiency
dataclassesβ modern replacement for verbose classesProtocolβ duck typing ka type-safe versionfunctools.lru_cacheβ instant memoizationpathlibβ never useos.pathagainf-stringsβ best string formatting, periodwalrus operator :=β write tighter loopsmatchstatement β structural pattern matching (3.10+)
Made with π β Your Bhai's Complete Python Bible