Python Backend Interview Master
Master Backend Excellence with 200+ Curated Python & Framework Questions
What is Python?
BeginnerPython is a high-level, interpreted, general-purpose programming language. It is known for its simplicity, readability, and vast library support, maki...
Comprehensive Answer:
Python is a high-level, interpreted, general-purpose programming language. It is known for its simplicity, readability, and vast library support, making it ideal for web development, data science, and automation.
What is the difference between list and tuple?
BeginnerLists are mutable (can be changed) and use square brackets []. Tuples are immutable (cannot be changed) and use parentheses (). Lists are generally sl...
Comprehensive Answer:
Lists are mutable (can be changed) and use square brackets []. Tuples are immutable (cannot be changed) and use parentheses (). Lists are generally slower than tuples.
What is PEP 8?
BeginnerPEP 8 is the official Style Guide for Python Code. It provides guidelines on how to format code to improve readability and consistency across the Pyth...
Comprehensive Answer:
PEP 8 is the official Style Guide for Python Code. It provides guidelines on how to format code to improve readability and consistency across the Python community.
How is memory managed in Python?
BeginnerPython uses a private heap to manage memory. It includes a built-in garbage collector that uses reference counting and a cycle-detecting algorithm to ...
Comprehensive Answer:
Python uses a private heap to manage memory. It includes a built-in garbage collector that uses reference counting and a cycle-detecting algorithm to reclaim unused memory.
What are Python namespaces?
BeginnerNamespaces are containers that store names (identifiers) mapping to objects. They ensure that names are unique and don't conflict, such as local, glob...
Comprehensive Answer:
Namespaces are containers that store names (identifiers) mapping to objects. They ensure that names are unique and don't conflict, such as local, global, and built-in namespaces.
What is the difference between 'is' and '=='?
Beginner'is' checks for identity (if two variables point to the same object in memory), while '==' checks for equality (if the values are the same).
Comprehensive Answer:
'is' checks for identity (if two variables point to the same object in memory), while '==' checks for equality (if the values are the same).
What are Python decorators?
BeginnerDecorators are a powerful way to modify or wrap the behavior of a function or class without changing its source code. They use the @decorator_name syn...
Comprehensive Answer:
Decorators are a powerful way to modify or wrap the behavior of a function or class without changing its source code. They use the @decorator_name syntax.
Explain list comprehension.
BeginnerList comprehension is a concise way to create lists based on existing lists or iterables. Example: [x*x for x in range(10) if x%2==0].
Comprehensive Answer:
List comprehension is a concise way to create lists based on existing lists or iterables. Example: [x*x for x in range(10) if x%2==0].
What is a docstring?
BeginnerA docstring (documentation string) is a string literal used as the first statement in a module, function, class, or method to describe its purpose. It...
Comprehensive Answer:
A docstring (documentation string) is a string literal used as the first statement in a module, function, class, or method to describe its purpose. It's accessed via the __doc__ attribute.
What are *args and **kwargs?
Beginner*args allows a function to accept any number of positional arguments as a tuple. **kwargs allows a function to accept any number of keyword arguments ...
Comprehensive Answer:
*args allows a function to accept any number of positional arguments as a tuple. **kwargs allows a function to accept any number of keyword arguments as a dictionary.
What is the difference between deep copy and shallow copy?
BeginnerA shallow copy creates a new object but references the nested objects of the original. A deep copy creates a new object and recursively copies all nes...
Comprehensive Answer:
A shallow copy creates a new object but references the nested objects of the original. A deep copy creates a new object and recursively copies all nested objects.
How do you handle exceptions in Python?
BeginnerUsing try, except, else, and finally blocks. Code that might fail goes in try, handling logic in except, success logic in else, and cleanup in finally...
Comprehensive Answer:
Using try, except, else, and finally blocks. Code that might fail goes in try, handling logic in except, success logic in else, and cleanup in finally.
What is the purpose of 'self' in classes?
Beginner'self' represents the instance of the class. It allows access to the attributes and methods of the specific object being worked with.
Comprehensive Answer:
'self' represents the instance of the class. It allows access to the attributes and methods of the specific object being worked with.
What is a lambda function?
BeginnerA lambda function is a small, anonymous, one-line function defined using the 'lambda' keyword. It can take any number of arguments but has only one ex...
Comprehensive Answer:
A lambda function is a small, anonymous, one-line function defined using the 'lambda' keyword. It can take any number of arguments but has only one expression.
Explain the 'with' statement.
BeginnerThe 'with' statement simplifies resource management (like file handling) by ensuring that resources are properly closed or released, even if an error ...
Comprehensive Answer:
The 'with' statement simplifies resource management (like file handling) by ensuring that resources are properly closed or released, even if an error occurs. It uses context managers.
What is 'pass' in Python?
Beginner'pass' is a null statement. It is used as a placeholder when a statement is syntactically required but no action is needed.
Comprehensive Answer:
'pass' is a null statement. It is used as a placeholder when a statement is syntactically required but no action is needed.
What is the difference between range and xrange?
BeginnerIn Python 2, range returns a list, while xrange returns an iterator (memory efficient). In Python 3, range behaves like xrange, and xrange no longer e...
Comprehensive Answer:
In Python 2, range returns a list, while xrange returns an iterator (memory efficient). In Python 3, range behaves like xrange, and xrange no longer exists.
How do you reverse a list?
BeginnerYou can use the list.reverse() method (in-place) or slicing [::-1] (creates a new list).
Comprehensive Answer:
You can use the list.reverse() method (in-place) or slicing [::-1] (creates a new list).
What are global and local variables?
BeginnerGlobal variables are defined outside any function and accessible throughout the module. Local variables are defined inside a function and only accessi...
Comprehensive Answer:
Global variables are defined outside any function and accessible throughout the module. Local variables are defined inside a function and only accessible within that function.
Explain the use of 'yield' keyword.
Beginner'yield' is used in functions to return a generator. Unlike 'return', it pauses the function's execution and saves its state, allowing it to resume lat...
Comprehensive Answer:
'yield' is used in functions to return a generator. Unlike 'return', it pauses the function's execution and saves its state, allowing it to resume later.
What is a dictionary in Python?
BeginnerA dictionary is an unordered, mutable collection of key-value pairs. Keys must be unique and immutable (hashable).
Comprehensive Answer:
A dictionary is an unordered, mutable collection of key-value pairs. Keys must be unique and immutable (hashable).
How do you comment in Python?
BeginnerUse the '#' symbol for single-line comments. For multi-line comments, triple quotes (''' or """) are often used as docstrings or multi-line strings.
Comprehensive Answer:
Use the '#' symbol for single-line comments. For multi-line comments, triple quotes (''' or """) are often used as docstrings or multi-line strings.
What is the difference between break, continue, and pass?
Beginner'break' exits the loop. 'continue' skips the current iteration. 'pass' does nothing (placeholder).
Comprehensive Answer:
'break' exits the loop. 'continue' skips the current iteration. 'pass' does nothing (placeholder).
How do you find the length of a string?
BeginnerUsing the built-in len() function. Example: len("hello").
Comprehensive Answer:
Using the built-in len() function. Example: len("hello").
What is slicing in Python?
BeginnerSlicing allows you to extract a portion of a sequence (list, string, tuple) using the [start:stop:step] syntax.
Comprehensive Answer:
Slicing allows you to extract a portion of a sequence (list, string, tuple) using the [start:stop:step] syntax.
Explain map() function.
Beginnermap() applies a given function to each item of an iterable (like a list) and returns an iterator with the results.
Comprehensive Answer:
map() applies a given function to each item of an iterable (like a list) and returns an iterator with the results.
Explain filter() function.
Beginnerfilter() constructs an iterator from elements of an iterable for which a function returns true.
Comprehensive Answer:
filter() constructs an iterator from elements of an iterable for which a function returns true.
Explain reduce() function.
Beginnerreduce() (from functools) applies a rolling computation to sequential pairs of values in an iterable, reducing it to a single value.
Comprehensive Answer:
reduce() (from functools) applies a rolling computation to sequential pairs of values in an iterable, reducing it to a single value.
What is an init method in Python?
BeginnerThe __init__ method is the constructor of a class. It is called automatically when an object is created to initialize its attributes.
Comprehensive Answer:
The __init__ method is the constructor of a class. It is called automatically when an object is created to initialize its attributes.
What is the difference between a set and a list?
BeginnerA list is an ordered collection that allows duplicates. A set is an unordered collection of unique elements.
Comprehensive Answer:
A list is an ordered collection that allows duplicates. A set is an unordered collection of unique elements.
How do you create a function in Python?
BeginnerUsing the 'def' keyword followed by the function name and parentheses. Example: def my_func(): pass
Comprehensive Answer:
Using the 'def' keyword followed by the function name and parentheses. Example: def my_func(): pass
What is a module in Python?
BeginnerA module is a file containing Python definitions and statements. It can be imported into other scripts using the 'import' keyword.
Comprehensive Answer:
A module is a file containing Python definitions and statements. It can be imported into other scripts using the 'import' keyword.
What is a package in Python?
BeginnerA package is a directory containing a collection of modules and a special __init__.py file (optional in modern Python).
Comprehensive Answer:
A package is a directory containing a collection of modules and a special __init__.py file (optional in modern Python).
Explain the use of 'global' keyword.
BeginnerThe 'global' keyword allows you to modify a variable defined at the global scope from within a function.
Comprehensive Answer:
The 'global' keyword allows you to modify a variable defined at the global scope from within a function.
Explain 'nonlocal' keyword.
Beginner'nonlocal' is used in nested functions to refer to a variable in the nearest enclosing scope (excluding global).
Comprehensive Answer:
'nonlocal' is used in nested functions to refer to a variable in the nearest enclosing scope (excluding global).
What is an iterable in Python?
BeginnerAn iterable is any object capable of returning its members one at a time, allowing it to be looped over in a for loop (e.g., list, string, dict).
Comprehensive Answer:
An iterable is any object capable of returning its members one at a time, allowing it to be looped over in a for loop (e.g., list, string, dict).
What is an iterator?
BeginnerAn iterator is an object that implements the iterator protocol (__iter__ and __next__ methods). It tracks the current position during iteration.
Comprehensive Answer:
An iterator is an object that implements the iterator protocol (__iter__ and __next__ methods). It tracks the current position during iteration.
What is a generator?
BeginnerA generator is a type of iterator created using a function with 'yield' or a generator expression. It produces values lazily (one at a time).
Comprehensive Answer:
A generator is a type of iterator created using a function with 'yield' or a generator expression. It produces values lazily (one at a time).
How do you convert a string to an integer?
BeginnerUsing the int() function. Example: int("10").
Comprehensive Answer:
Using the int() function. Example: int("10").
How do you check the type of an object?
BeginnerUsing the type() function or isinstance() (preferred for inheritance checks).
Comprehensive Answer:
Using the type() function or isinstance() (preferred for inheritance checks).
What is the use of 'dir()' function?
Beginnerdir() returns a list of valid attributes and methods for an object or the current local scope.
Comprehensive Answer:
dir() returns a list of valid attributes and methods for an object or the current local scope.
What is 'help()' in Python?
Beginnerhelp() is a built-in function used to display documentation for modules, classes, functions, and keywords.
Comprehensive Answer:
help() is a built-in function used to display documentation for modules, classes, functions, and keywords.
How do you read input from a user?
BeginnerUsing the input() function. It always returns the input as a string.
Comprehensive Answer:
Using the input() function. It always returns the input as a string.
What is the difference between append() and extend()?
Beginnerappend() adds a single element to the end of a list. extend() adds all elements of an iterable to the end of the list.
Comprehensive Answer:
append() adds a single element to the end of a list. extend() adds all elements of an iterable to the end of the list.
What is 'join()' method in strings?
Beginnerjoin() concatenates elements of an iterable (like a list of strings) using a separator string. Example: ", ".join(["a", "b"]).
Comprehensive Answer:
join() concatenates elements of an iterable (like a list of strings) using a separator string. Example: ", ".join(["a", "b"]).
What is 'split()' method?
Beginnersplit() breaks a string into a list of substrings based on a delimiter (default is whitespace).
Comprehensive Answer:
split() breaks a string into a list of substrings based on a delimiter (default is whitespace).
Explain 'getattr' and 'setattr'.
Beginnergetattr(obj, name) gets the value of an attribute by name. setattr(obj, name, value) sets the value of an attribute by name.
Comprehensive Answer:
getattr(obj, name) gets the value of an attribute by name. setattr(obj, name, value) sets the value of an attribute by name.
What is the difference between sorted() and sort()?
Beginnersorted() returns a new sorted list from an iterable. sort() sorts the list in-place and returns None.
Comprehensive Answer:
sorted() returns a new sorted list from an iterable. sort() sorts the list in-place and returns None.
What is a Boolean in Python?
BeginnerA data type that can have one of two values: True or False. Note the capitalization.
Comprehensive Answer:
A data type that can have one of two values: True or False. Note the capitalization.
How do you open a file for writing?
BeginnerUsing open("filename", "w"). "w" overwrites the file, while "a" appends to it.
Comprehensive Answer:
Using open("filename", "w"). "w" overwrites the file, while "a" appends to it.
Explain the Python Global Interpreter Lock (GIL).
ExperienceThe GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes at once. This simplifies...
Comprehensive Answer:
The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes at once. This simplifies memory management but limits multi-core performance for CPU-bound tasks.
How do you bypass the GIL?
ExperienceUsing the multiprocessing module (separate processes), using C extensions that release the GIL, or for I/O bound tasks, using threading or asyncio.
Comprehensive Answer:
Using the multiprocessing module (separate processes), using C extensions that release the GIL, or for I/O bound tasks, using threading or asyncio.
What is the difference between Threading and Multiprocessing?
ExperienceThreading shares the same memory space (efficient but limited by GIL). Multiprocessing creates separate memory spaces (sidesteps GIL, better for CPU-b...
Comprehensive Answer:
Threading shares the same memory space (efficient but limited by GIL). Multiprocessing creates separate memory spaces (sidesteps GIL, better for CPU-bound tasks, but higher overhead).
Explain 'Monkey Patching'.
ExperienceMonkey patching is the practice of modifying or extending the behavior of a module or class at runtime, often used for testing or bug fixes without ch...
Comprehensive Answer:
Monkey patching is the practice of modifying or extending the behavior of a module or class at runtime, often used for testing or bug fixes without changing source code.
What are 'Class Methods' and 'Static Methods'?
ExperienceClass methods (@classmethod) take 'cls' as the first argument and can access class-level state. Static methods (@staticmethod) don't take an implicit ...
Comprehensive Answer:
Class methods (@classmethod) take 'cls' as the first argument and can access class-level state. Static methods (@staticmethod) don't take an implicit first argument and behave like regular functions inside a class namespace.
Explain 'MRO' (Method Resolution Order).
ExperienceMRO is the order in which Python searches for base classes when a method is called. Python uses the C3 Linearization algorithm to determine this order...
Comprehensive Answer:
MRO is the order in which Python searches for base classes when a method is called. Python uses the C3 Linearization algorithm to determine this order.
What is 'super()'?
Experiencesuper() is used to call methods of a parent class or sibling class. It handles MRO correctly, ensuring that each parent is called only once.
Comprehensive Answer:
super() is used to call methods of a parent class or sibling class. It handles MRO correctly, ensuring that each parent is called only once.
What are 'Metaclasses'?
ExperienceMetaclasses are 'classes of classes'. They define how a class is constructed. The default metaclass is 'type'. You can use them to automatically modif...
Comprehensive Answer:
Metaclasses are 'classes of classes'. They define how a class is constructed. The default metaclass is 'type'. You can use them to automatically modify classes during creation.
Explain 'Abstract Base Classes' (ABCs).
ExperienceABCs (from 'abc' module) define a set of methods that a subclass must implement. They cannot be instantiated directly and are used to define interface...
Comprehensive Answer:
ABCs (from 'abc' module) define a set of methods that a subclass must implement. They cannot be instantiated directly and are used to define interfaces.
What is 'Pickling' and 'Unpickling'?
ExperiencePickling is the process of converting a Python object into a byte stream (serialization). Unpickling is the reverse (deserialization).
Comprehensive Answer:
Pickling is the process of converting a Python object into a byte stream (serialization). Unpickling is the reverse (deserialization).
What is a Context Manager?
ExperienceAn object that defines the runtime context when executing a 'with' statement. It implements __enter__ and __exit__ methods.
Comprehensive Answer:
An object that defines the runtime context when executing a 'with' statement. It implements __enter__ and __exit__ methods.
How do you create a custom Context Manager?
ExperienceBy implementing a class with __enter__ and __exit__, or using the @contextmanager decorator from contextlib module.
Comprehensive Answer:
By implementing a class with __enter__ and __exit__, or using the @contextmanager decorator from contextlib module.
Explain 'Duck Typing'.
ExperienceA programming style where an object's suitability is determined by the presence of certain methods and properties, rather than its actual type ('If it...
Comprehensive Answer:
A programming style where an object's suitability is determined by the presence of certain methods and properties, rather than its actual type ('If it walks like a duck and quacks like a duck, it's a duck').
What is 'F-strings' in Python?
ExperienceFormatted string literals (introduced in 3.6) that use f"..." syntax. They allow embedding expressions inside curly braces for concise and performant ...
Comprehensive Answer:
Formatted string literals (introduced in 3.6) that use f"..." syntax. They allow embedding expressions inside curly braces for concise and performant string formatting.
Explain 'Property' decorator.
Experience@property allows you to define a method that can be accessed like an attribute. It's used for encapsulation and validation (getter/setter/deleter).
Comprehensive Answer:
@property allows you to define a method that can be accessed like an attribute. It's used for encapsulation and validation (getter/setter/deleter).
What is 'Descriptor' in Python?
ExperienceA descriptor is an object that defines __get__, __set__, or __delete__ for an attribute. Built-in descriptors include property, classmethod, and stati...
Comprehensive Answer:
A descriptor is an object that defines __get__, __set__, or __delete__ for an attribute. Built-in descriptors include property, classmethod, and staticmethod.
What is 'slots' in Python classes?
Experience__slots__ is a list of attributes that limits the attributes an instance can have. It saves memory by preventing the creation of the __dict__ for each...
Comprehensive Answer:
__slots__ is a list of attributes that limits the attributes an instance can have. It saves memory by preventing the creation of the __dict__ for each instance.
Explain 'Walrus Operator' (:=).
ExperienceIntroduced in 3.8, it allows you to assign a value to a variable as part of an expression. Example: if (n := len(data)) > 10: print(n).
Comprehensive Answer:
Introduced in 3.8, it allows you to assign a value to a variable as part of an expression. Example: if (n := len(data)) > 10: print(n).
What is the difference between 'asyncio' and 'threading'?
ExperienceThreading uses OS-level pre-emptive multitasking. Asyncio uses cooperative multitasking (event loop) on a single thread. Asyncio is better for scaling...
Comprehensive Answer:
Threading uses OS-level pre-emptive multitasking. Asyncio uses cooperative multitasking (event loop) on a single thread. Asyncio is better for scaling high-concurrency I/O.
Explain 'Coroutine'.
ExperienceA coroutine is a specialized generator-like object defined with 'async def'. It can pause execution (await) and yield control back to the event loop.
Comprehensive Answer:
A coroutine is a specialized generator-like object defined with 'async def'. It can pause execution (await) and yield control back to the event loop.
What is 'FastAPI'?
ExperienceA modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It is extremely fast due to Starlette...
Comprehensive Answer:
A modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It is extremely fast due to Starlette and Pydantic.
What is 'Django'?
ExperienceA high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the 'batteries included' philosophy.
Comprehensive Answer:
A high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the 'batteries included' philosophy.
What is 'Flask'?
ExperienceA micro web framework for Python. It is lightweight and modular, allowing developers to choose their own tools and libraries.
Comprehensive Answer:
A micro web framework for Python. It is lightweight and modular, allowing developers to choose their own tools and libraries.
What is 'WSGI' vs 'ASGI'?
ExperienceWSGI (Web Server Gateway Interface) is synchronous. ASGI (Asynchronous Server Gateway Interface) supports asynchronous features like WebSockets and HT...
Comprehensive Answer:
WSGI (Web Server Gateway Interface) is synchronous. ASGI (Asynchronous Server Gateway Interface) supports asynchronous features like WebSockets and HTTP/2.
Explain 'Pydantic'.
ExperienceA library used for data validation and settings management using Python type annotations. It's heavily used in FastAPI.
Comprehensive Answer:
A library used for data validation and settings management using Python type annotations. It's heavily used in FastAPI.
What is 'Celery'?
ExperienceAn asynchronous task queue/job queue based on distributed message passing. It's used for running background tasks in web applications.
Comprehensive Answer:
An asynchronous task queue/job queue based on distributed message passing. It's used for running background tasks in web applications.
What is 'Alembic'?
ExperienceA lightweight database migration tool for use with SQLAlchemy. It handles evolution of database schemas over time.
Comprehensive Answer:
A lightweight database migration tool for use with SQLAlchemy. It handles evolution of database schemas over time.
Explain 'SQLAlchemy'.
ExperienceA powerful SQL toolkit and Object Relational Mapper (ORM) that gives developers the full power and flexibility of SQL.
Comprehensive Answer:
A powerful SQL toolkit and Object Relational Mapper (ORM) that gives developers the full power and flexibility of SQL.
What is 'Unit Testing' in Python?
ExperienceTesting individual components of code in isolation. Common libraries include 'unittest' (built-in) and 'pytest' (popular third-party).
Comprehensive Answer:
Testing individual components of code in isolation. Common libraries include 'unittest' (built-in) and 'pytest' (popular third-party).
What is 'Mocking' in testing?
ExperienceThe process of replacing parts of your system with mock objects that simulate their behavior, allowing you to isolate the code being tested.
Comprehensive Answer:
The process of replacing parts of your system with mock objects that simulate their behavior, allowing you to isolate the code being tested.
Explain 'Pytest' fixtures.
ExperienceFixtures are functions that run before (and optionally after) tests to provide setup and teardown logic (e.g., DB connections, test data).
Comprehensive Answer:
Fixtures are functions that run before (and optionally after) tests to provide setup and teardown logic (e.g., DB connections, test data).
What is 'Virtual Environment'?
ExperienceA tool to create isolated Python environments where you can install dependencies without affecting the global system Python.
Comprehensive Answer:
A tool to create isolated Python environments where you can install dependencies without affecting the global system Python.
What is the 'PyPi'?
ExperienceThe Python Package Index (PyPI) is the official repository for third-party Python software packages.
Comprehensive Answer:
The Python Package Index (PyPI) is the official repository for third-party Python software packages.
Explain 'Pipenv' and 'Poetry'.
ExperienceModern dependency management tools that replace pip and virtualenv. They provide deterministic builds using lock files.
Comprehensive Answer:
Modern dependency management tools that replace pip and virtualenv. They provide deterministic builds using lock files.
What is 'Gunicorn'?
ExperienceA Python WSGI HTTP Server for UNIX. It is a pre-fork worker model and is commonly used to deploy Django and Flask apps.
Comprehensive Answer:
A Python WSGI HTTP Server for UNIX. It is a pre-fork worker model and is commonly used to deploy Django and Flask apps.
What is 'Uvicorn'?
ExperienceA lightning-fast ASGI server implementation, used for running FastAPI and other asynchronous web frameworks.
Comprehensive Answer:
A lightning-fast ASGI server implementation, used for running FastAPI and other asynchronous web frameworks.
Explain 'CORS' in web APIs.
ExperienceCross-Origin Resource Sharing is a security feature that controls which domains can access your API resources.
Comprehensive Answer:
Cross-Origin Resource Sharing is a security feature that controls which domains can access your API resources.
What is 'JWT' in Python?
ExperienceJSON Web Tokens are used for secure authentication. Libraries like PyJWT are used to encode and decode tokens.
Comprehensive Answer:
JSON Web Tokens are used for secure authentication. Libraries like PyJWT are used to encode and decode tokens.
Explain 'Session' vs 'Token' based authentication.
ExperienceSessions are stored on the server (stateful). Tokens (like JWT) are stored on the client (stateless), making them better for scaling.
Comprehensive Answer:
Sessions are stored on the server (stateful). Tokens (like JWT) are stored on the client (stateless), making them better for scaling.
What is 'Middleware' in Django/FastAPI?
ExperienceCode that sits between the request and response. It can inspect/modify requests before they reach the view or responses before they reach the client.
Comprehensive Answer:
Code that sits between the request and response. It can inspect/modify requests before they reach the view or responses before they reach the client.
Explain 'Nginx' role in deployment.
ExperienceNginx acts as a reverse proxy, load balancer, and static file server, sitting in front of the application server (Gunicorn/Uvicorn).
Comprehensive Answer:
Nginx acts as a reverse proxy, load balancer, and static file server, sitting in front of the application server (Gunicorn/Uvicorn).
How to handle 'Recursive Queries' in ORM?
ExperienceUsing Common Table Expressions (CTEs) or specific ORM features like 'adjacency list' patterns for hierarchical data.
Comprehensive Answer:
Using Common Table Expressions (CTEs) or specific ORM features like 'adjacency list' patterns for hierarchical data.
Explain 'N+1 Query Problem'.
ExperienceA performance issue where the ORM executes one query to get a list and then N additional queries to get related data for each item. Solved using 'eage...
Comprehensive Answer:
A performance issue where the ORM executes one query to get a list and then N additional queries to get related data for each item. Solved using 'eager loading' (select_related/prefetch_related).
What is 'Redis' used for in Python backends?
ExperienceCaching, session storage, real-time analytics, and as a message broker for Celery.
Comprehensive Answer:
Caching, session storage, real-time analytics, and as a message broker for Celery.
Explain 'WebSockets' in Python.
ExperienceA protocol for real-time, full-duplex communication over a single TCP connection. Supported by ASGI frameworks like FastAPI and Django Channels.
Comprehensive Answer:
A protocol for real-time, full-duplex communication over a single TCP connection. Supported by ASGI frameworks like FastAPI and Django Channels.
How to perform 'Profiling' in Python?
ExperienceUsing the 'cProfile' module to measure where the time is spent in your application.
Comprehensive Answer:
Using the 'cProfile' module to measure where the time is spent in your application.
What is 'Circular Import' and how to fix it?
ExperienceOccurs when Module A imports B and B imports A. Fix by refactoring, using local imports inside functions, or moving imports to the bottom.
Comprehensive Answer:
Occurs when Module A imports B and B imports A. Fix by refactoring, using local imports inside functions, or moving imports to the bottom.
Explain 'Weakref'.
ExperienceA weak reference is a reference that doesn't prevent its object from being garbage collected. Useful for caches.
Comprehensive Answer:
A weak reference is a reference that doesn't prevent its object from being garbage collected. Useful for caches.
What is 'Itertools' module?
ExperienceA collection of functions that create iterators for efficient looping (e.g., chain, cycle, groupby, product).
Comprehensive Answer:
A collection of functions that create iterators for efficient looping (e.g., chain, cycle, groupby, product).
What is 'Functools' module?
ExperienceHigher-order functions for working with functions (e.g., lru_cache for memoization, partial for pre-filling arguments).
Comprehensive Answer:
Higher-order functions for working with functions (e.g., lru_cache for memoization, partial for pre-filling arguments).
How does Python's Garbage Collector work?
AdvancedPrimary mechanism is reference counting. For cyclic references, it uses a generational collector that periodically scans three 'generations' of object...
Comprehensive Answer:
Primary mechanism is reference counting. For cyclic references, it uses a generational collector that periodically scans three 'generations' of objects.
Explain 'Bytecode' vs 'Machine Code'.
AdvancedBytecode (.pyc) is an intermediate representation optimized for the Python Virtual Machine (PVM). Machine code is what the CPU understands. CPython is...
Comprehensive Answer:
Bytecode (.pyc) is an intermediate representation optimized for the Python Virtual Machine (PVM). Machine code is what the CPU understands. CPython is an interpreter that compiles to bytecode.
What is 'JIT' Compilation in Python?
AdvancedJust-In-Time compilation (used in PyPy) compiles hot spots of code directly to machine code for significantly better performance.
Comprehensive Answer:
Just-In-Time compilation (used in PyPy) compiles hot spots of code directly to machine code for significantly better performance.
Explain 'Frame Objects' in Python.
AdvancedFrames track the execution of a block of code (like a function). They contain the local namespace, the stack, and references to previous frames.
Comprehensive Answer:
Frames track the execution of a block of code (like a function). They contain the local namespace, the stack, and references to previous frames.
What is 'Introspection' in Python?
AdvancedThe ability of a program to examine the type or properties of an object at runtime using functions like hasattr(), getattr(), dir(), type().
Comprehensive Answer:
The ability of a program to examine the type or properties of an object at runtime using functions like hasattr(), getattr(), dir(), type().
How to optimize Python for performance?
AdvancedUse built-in functions, avoid global variables, use local variables, use joins for strings, use generator expressions, use C extensions (Cython/Numba)...
Comprehensive Answer:
Use built-in functions, avoid global variables, use local variables, use joins for strings, use generator expressions, use C extensions (Cython/Numba).
Explain 'descriptors' deep dive.
AdvancedData descriptors implement both __get__ and __set__. Non-data descriptors only implement __get__. Data descriptors take precedence over instance __dic...
Comprehensive Answer:
Data descriptors implement both __get__ and __set__. Non-data descriptors only implement __get__. Data descriptors take precedence over instance __dict__ entries.
What is 'Zero-copy' in Python?
AdvancedTechniques to avoid copying data in memory during I/O, often using 'memoryview' and 'buffer protocol'.
Comprehensive Answer:
Techniques to avoid copying data in memory during I/O, often using 'memoryview' and 'buffer protocol'.
Explain 'Memoryview'.
AdvancedA built-in that allows you to access internal buffers of objects (like bytes) without copying the data. Essential for performance in large data proces...
Comprehensive Answer:
A built-in that allows you to access internal buffers of objects (like bytes) without copying the data. Essential for performance in large data processing.
Security: What is 'SQL Injection' and how to prevent it?
AdvancedAn attack where malicious SQL is injected into queries. Prevent by using parameterized queries (provided by almost all Python DB drivers and ORMs).
Comprehensive Answer:
An attack where malicious SQL is injected into queries. Prevent by using parameterized queries (provided by almost all Python DB drivers and ORMs).
Security: What is 'XSS' in Python web apps?
AdvancedCross-Site Scripting. Prevent by auto-escaping templates (Django/Jinja2 do this) and validating all user inputs.
Comprehensive Answer:
Cross-Site Scripting. Prevent by auto-escaping templates (Django/Jinja2 do this) and validating all user inputs.
Explain 'Microservices' communication in Python.
AdvancedSynchronous (HTTP/gRPC) or Asynchronous (RabbitMQ/Kafka/Selaery).
Comprehensive Answer:
Synchronous (HTTP/gRPC) or Asynchronous (RabbitMQ/Kafka/Selaery).
What is 'gRPC' in Python?
AdvancedA high-performance RPC framework using Protocol Buffers and HTTP/2. Better for internal microservice communication than REST.
Comprehensive Answer:
A high-performance RPC framework using Protocol Buffers and HTTP/2. Better for internal microservice communication than REST.
Explain 'Saga Pattern' in distributed transactions.
AdvancedA sequence of local transactions where each one updates the DB and publishes an event to trigger the next one. Handles failures with 'compensation' tr...
Comprehensive Answer:
A sequence of local transactions where each one updates the DB and publishes an event to trigger the next one. Handles failures with 'compensation' transactions.
What is 'CAP Theorem'?
AdvancedConsistency, Availability, and Partition Tolerance. A distributed system can only guarantee two of the three.
Comprehensive Answer:
Consistency, Availability, and Partition Tolerance. A distributed system can only guarantee two of the three.
Explain 'Horizontal' vs 'Vertical' Scaling.
AdvancedHorizontal: adding more machines (stateless apps are easier). Vertical: adding more CPU/RAM to one machine.
Comprehensive Answer:
Horizontal: adding more machines (stateless apps are easier). Vertical: adding more CPU/RAM to one machine.
What is 'Serverless' in Python backend?
AdvancedDeploying individual functions (AWS Lambda/Google Cloud Functions) that scale automatically. Python is great for this due to small startup times.
Comprehensive Answer:
Deploying individual functions (AWS Lambda/Google Cloud Functions) that scale automatically. Python is great for this due to small startup times.
Explain 'Clean Architecture' in Python.
AdvancedOrganizing code into layers (Entities, Use Cases, Adapters) to keep business logic independent of external frameworks/DBs.
Comprehensive Answer:
Organizing code into layers (Entities, Use Cases, Adapters) to keep business logic independent of external frameworks/DBs.
What is 'Twelve-Factor App' methodology?
AdvancedA set of best practices for building scalable, maintainable SaaS apps (e.g., config in env, stateless processes, dev/prod parity).
Comprehensive Answer:
A set of best practices for building scalable, maintainable SaaS apps (e.g., config in env, stateless processes, dev/prod parity).
Explain 'Consistent Hashing'.
AdvancedA technique used in distributed caching (like Redis Cluster) to minimize data movement when nodes are added or removed.
Comprehensive Answer:
A technique used in distributed caching (like Redis Cluster) to minimize data movement when nodes are added or removed.
What is 'Database Sharding'?
AdvancedSplitting a large database into smaller pieces (shards) across different servers to improve performance and capacity.
Comprehensive Answer:
Splitting a large database into smaller pieces (shards) across different servers to improve performance and capacity.
Explain 'Rate Limiting' algorithms.
AdvancedToken Bucket, Leaky Bucket, Fixed Window, and Sliding Window logs. Important for API stability.
Comprehensive Answer:
Token Bucket, Leaky Bucket, Fixed Window, and Sliding Window logs. Important for API stability.
What is 'Circuit Breaker' in Python microservices?
AdvancedA pattern to detect failures and encapsulate the logic of preventing a failure from cascading. Libraries like 'poly' help here.
Comprehensive Answer:
A pattern to detect failures and encapsulate the logic of preventing a failure from cascading. Libraries like 'poly' help here.
How to handle 'Distributed Tracing'?
AdvancedUsing OpenTelemetry, Jaeger, or Zipkin to track requests as they flow through multiple services.
Comprehensive Answer:
Using OpenTelemetry, Jaeger, or Zipkin to track requests as they flow through multiple services.
Explain 'Event Sourcing'.
AdvancedStoring the state of the system as a sequence of events rather than just the current state.
Comprehensive Answer:
Storing the state of the system as a sequence of events rather than just the current state.
What is 'CQRS'?
AdvancedCommand Query Responsibility Segregation. Splitting read and write operations into different models for better performance and scalability.
Comprehensive Answer:
Command Query Responsibility Segregation. Splitting read and write operations into different models for better performance and scalability.
Deep Dive: 'asyncio' event loop internals.
AdvancedUses selectors to wait for I/O events. Tasks are scheduled and run on a single thread. It maintains a ready queue and a scheduled queue.
Comprehensive Answer:
Uses selectors to wait for I/O events. Tasks are scheduled and run on a single thread. It maintains a ready queue and a scheduled queue.
What is 'Contextvars'?
AdvancedA module for managing context-local state that works across asynchronous tasks (unlike threading.local).
Comprehensive Answer:
A module for managing context-local state that works across asynchronous tasks (unlike threading.local).
Explain 'Data Classes' vs 'NamedTuple'.
AdvancedDataClasses are mutable and feature-rich. NamedTuples are immutable and more memory-efficient.
Comprehensive Answer:
DataClasses are mutable and feature-rich. NamedTuples are immutable and more memory-efficient.
What is 'Type Checking' in Python production?
AdvancedUsing static type checkers like Mypy, Pyright, or Pytype to find bugs before runtime.
Comprehensive Answer:
Using static type checkers like Mypy, Pyright, or Pytype to find bugs before runtime.
Explain 'Cython'.
AdvancedA language that serves as a superset of Python, allowing you to write C extensions with Python-like syntax for extreme performance.
Comprehensive Answer:
A language that serves as a superset of Python, allowing you to write C extensions with Python-like syntax for extreme performance.
What is 'Numba'?
AdvancedAn open-source JIT compiler that translates a subset of Python and NumPy code into fast machine code using LLVM.
Comprehensive Answer:
An open-source JIT compiler that translates a subset of Python and NumPy code into fast machine code using LLVM.
How to implement 'Custom Import Hooks'?
AdvancedUsing the importlib module and implementing meta path finders and loaders.
Comprehensive Answer:
Using the importlib module and implementing meta path finders and loaders.
Explain 'interning' in Python strings.
AdvancedPython automatically caches short strings and identifiers to save memory and speed up comparisons (sys.intern() can be used manually).
Comprehensive Answer:
Python automatically caches short strings and identifiers to save memory and speed up comparisons (sys.intern() can be used manually).
What is 'object.__new__'?
AdvancedThe static method that actually creates the object, while __init__ initializes it. Used mostly in metaclasses and singletons.
Comprehensive Answer:
The static method that actually creates the object, while __init__ initializes it. Used mostly in metaclasses and singletons.
Explain 'Python Object Model'.
AdvancedEverything in Python is an object, including types and functions. Objects have an ID, type, and value.
Comprehensive Answer:
Everything in Python is an object, including types and functions. Objects have an ID, type, and value.
What is 'C3 Linearization'?
AdvancedThe algorithm Python uses to compute Method Resolution Order (MRO) for multiple inheritance.
Comprehensive Answer:
The algorithm Python uses to compute Method Resolution Order (MRO) for multiple inheritance.
How to handle 'Heavy Background Jobs' in Django?
AdvancedOffload to Celery or Dramatiq using Redis or RabbitMQ as a broker.
Comprehensive Answer:
Offload to Celery or Dramatiq using Redis or RabbitMQ as a broker.
Explain 'Optimistic' vs 'Pessimistic' Locking.
AdvancedPessimistic: Locks the row (SELECT FOR UPDATE). Optimistic: Checks for changes at the end (using version/timestamp columns).
Comprehensive Answer:
Pessimistic: Locks the row (SELECT FOR UPDATE). Optimistic: Checks for changes at the end (using version/timestamp columns).
What is 'Query Optimization' techniques?
AdvancedIndexes, Explain Plan, Partial Indexes, Covering Indexes, Denormalization when needed.
Comprehensive Answer:
Indexes, Explain Plan, Partial Indexes, Covering Indexes, Denormalization when needed.
Explain 'Blue-Green' vs 'Canary' deployment.
AdvancedBlue-Green: Swapping two identical environments. Canary: Slowly Rolling out to a small subset of users.
Comprehensive Answer:
Blue-Green: Swapping two identical environments. Canary: Slowly Rolling out to a small subset of users.
What is 'Sidecar Pattern' in K8s (Python context)?
AdvancedAn auxiliary container (e.g., logging/proxy) running alongside your Python container in the same pod.
Comprehensive Answer:
An auxiliary container (e.g., logging/proxy) running alongside your Python container in the same pod.
How to secure 'Sensitive Config'?
AdvancedUse Secrets Managers (AWS Secrets Manager, HashiCorp Vault) and inject via env vars.
Comprehensive Answer:
Use Secrets Managers (AWS Secrets Manager, HashiCorp Vault) and inject via env vars.
Explain 'Zero-Downtime' migrations.
AdvancedTwo-step process: Add new column (nullable), backfill, then remove old logic/column in next release.
Comprehensive Answer:
Two-step process: Add new column (nullable), backfill, then remove old logic/column in next release.
What is 'Thundering Herd' problem in Cache?
AdvancedWhen many clients request a stale cache entry at once, causing a surge on the database. Fix with 'locking' or 'probabilistic early expiration'.
Comprehensive Answer:
When many clients request a stale cache entry at once, causing a surge on the database. Fix with 'locking' or 'probabilistic early expiration'.
Explain 'GraphQL' in Python Backend.
AdvancedA query language for APIs. Libraries like Graphene or Ariadne are used with Python frameworks.
Comprehensive Answer:
A query language for APIs. Libraries like Graphene or Ariadne are used with Python frameworks.
What is 'Web Scraping' ethical/technical considerations?
AdvancedRobots.txt, rate limiting, human-like behavior (rotating UX), using BeautifulSoup or Scrapy.
Comprehensive Answer:
Robots.txt, rate limiting, human-like behavior (rotating UX), using BeautifulSoup or Scrapy.
Explain 'Observability' vs 'Monitoring'.
AdvancedMonitoring tells you 'what' went wrong. Observability tells you 'why', using logs, metrics, and traces.
Comprehensive Answer:
Monitoring tells you 'what' went wrong. Observability tells you 'why', using logs, metrics, and traces.
How to implement 'Multi-tenancy'?
AdvancedShared DB with ID, Schema-based, or separate DBs per tenant.
Comprehensive Answer:
Shared DB with ID, Schema-based, or separate DBs per tenant.
What is 'Chaos Engineering' in Python backend?
AdvancedPurposely breaking things in production (e.g., killing a pod) to ensure the system is resilient.
Comprehensive Answer:
Purposely breaking things in production (e.g., killing a pod) to ensure the system is resilient.
Fibonacci sequence generator.
BeginnerUse a generator for memory efficiency.
Comprehensive Answer:
Use a generator for memory efficiency.
Code Snippet:
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + bCheck if a string is a palindrome.
BeginnerUse slicing.
Comprehensive Answer:
Use slicing.
Code Snippet:
def is_pal(s):
return s == s[::-1]Find duplicate items in a list.
BeginnerUse a set or dictionary.
Comprehensive Answer:
Use a set or dictionary.
Code Snippet:
def finds_dups(l):
return set([x for x in l if l.count(x) > 1])Sort a list of dictionaries by a key.
BeginnerUse sorted() with a lambda or itemgetter.
Comprehensive Answer:
Use sorted() with a lambda or itemgetter.
Code Snippet:
sorted(data, key=lambda x: x['age'])Read a file line by line.
BeginnerIterate over the file object.
Comprehensive Answer:
Iterate over the file object.
Code Snippet:
with open('f.txt') as f:
for line in f:
print(line)Flatten a nested list.
ExperienceUse recursion or a nested comprehension.
Comprehensive Answer:
Use recursion or a nested comprehension.
Code Snippet:
def flatten(l):
return [item for sub in l for item in sub]Group list items by frequency.
ExperienceUse collections.Counter.
Comprehensive Answer:
Use collections.Counter.
Code Snippet:
from collections import Counter
counts = Counter([1, 2, 2, 3])Implement a simple decorator.
ExperienceFunction returning a wrapper.
Comprehensive Answer:
Function returning a wrapper.
Code Snippet:
def my_dec(f):
def wrapper(*a, **k):
print('Start')
return f(*a, **k)
return wrapperMerge two dictionaries.
BeginnerUse | (3.9+) or {**d1, **d2}.
Comprehensive Answer:
Use | (3.9+) or {**d1, **d2}.
Code Snippet:
merged = d1 | d2Factorial using recursion.
BeginnerStandard recursive call.
Comprehensive Answer:
Standard recursive call.
Code Snippet:
def fact(n):
return 1 if n <= 1 else n * fact(n-1)Check if all items in list are unique.
BeginnerCompare length with set length.
Comprehensive Answer:
Compare length with set length.
Code Snippet:
len(l) == len(set(l))Convert list of tuples to dictionary.
BeginnerUse dict() constructor.
Comprehensive Answer:
Use dict() constructor.
Code Snippet:
d = dict([('a', 1), ('b', 2)])Find the intersection of two lists.
BeginnerUse set intersection.
Comprehensive Answer:
Use set intersection.
Code Snippet:
intersect = list(set(l1) & set(l2))Implement a Singleton pattern.
ExperienceUsing __new__.
Comprehensive Answer:
Using __new__.
Code Snippet:
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instanceFilter even numbers from a list.
BeginnerList comprehension.
Comprehensive Answer:
List comprehension.
Code Snippet:
[x for x in l if x % 2 == 0]Reverse words in a sentence.
BeginnerSplit, reverse, join.
Comprehensive Answer:
Split, reverse, join.
Code Snippet:
' '.join(s.split()[::-1])Find the most common element in a list.
BeginnerCounter.most_common().
Comprehensive Answer:
Counter.most_common().
Code Snippet:
Counter(l).most_common(1)Measure execution time of a function.
ExperienceUse time module.
Comprehensive Answer:
Use time module.
Code Snippet:
import time
start = time.time()
func()
print(time.time() - start)Convert snake_case to CamelCase.
ExperienceSplit and title().
Comprehensive Answer:
Split and title().
Code Snippet:
''.join(x.title() for x in s.split('_'))Get the last N items of a list.
BeginnerSlicing.
Comprehensive Answer:
Slicing.
Code Snippet:
l[-n:]Implement Binary Search.
ExperienceIterative approach.
Comprehensive Answer:
Iterative approach.
Code Snippet:
while low <= high:
mid = (low+high)//2
# comparison...Chunk a list into smaller pieces.
ExperienceSlicing in a loop.
Comprehensive Answer:
Slicing in a loop.
Code Snippet:
[l[i:i+n] for i in range(0, len(l), n)]Remove whitespace from string.
Beginnerstrip() or replace().
Comprehensive Answer:
strip() or replace().
Code Snippet:
s.replace(' ', '')Generate a random string.
Experiencestring and random modules.
Comprehensive Answer:
string and random modules.
Code Snippet:
''.join(random.choice(string.ascii_letters) for _ in range(10))Check if a variable is an integer.
Beginnerisinstance().
Comprehensive Answer:
isinstance().
Code Snippet:
isinstance(v, int)Remove None values from a list.
BeginnerFilter.
Comprehensive Answer:
Filter.
Code Snippet:
[x for x in l if x is not None]Get current date and time.
Beginnerdatetime module.
Comprehensive Answer:
datetime module.
Code Snippet:
from datetime import datetime
now = datetime.now()Format a date string.
Beginnerstrftime().
Comprehensive Answer:
strftime().
Code Snippet:
now.strftime('%Y-%m-%d')Exception chaining.
ExperienceUsing 'from'.
Comprehensive Answer:
Using 'from'.
Code Snippet:
raise NewError from old_errorDeep clone an object.
Experiencecopy.deepcopy().
Comprehensive Answer:
copy.deepcopy().
Code Snippet:
import copy
new_obj = copy.deepcopy(old_obj)Check for prime numbers.
BeginnerLoop check.
Comprehensive Answer:
Loop check.
Code Snippet:
all(n % i for i in range(2, int(n**0.5) + 1))Find missing number in array.
ExperienceSum difference.
Comprehensive Answer:
Sum difference.
Code Snippet:
sum(range(n+1)) - sum(arr)Implement a stack.
BeginnerUse a list with append/pop.
Comprehensive Answer:
Use a list with append/pop.
Code Snippet:
s = []
s.append(1)
s.pop()Implement a queue.
BeginnerUse collections.deque.
Comprehensive Answer:
Use collections.deque.
Code Snippet:
from collections import deque
q = deque()
q.append(1)
q.popleft()Map function to nested list.
ExperienceRecursion.
Comprehensive Answer:
Recursion.
Code Snippet:
def map_nested(f, l):
return [map_nested(f, x) if isinstance(x, list) else f(x) for x in l]Intersection of two dictionaries.
ExperienceDict comprehension with intersection.
Comprehensive Answer:
Dict comprehension with intersection.
Code Snippet:
{k: d1[k] for k in d1.keys() & d2.keys()}How to read environment variables.
Beginneros.environ.
Comprehensive Answer:
os.environ.
Code Snippet:
import os
val = os.environ.get('KEY')Zip two lists into a dictionary.
Beginnerdict(zip(l1, l2)).
Comprehensive Answer:
dict(zip(l1, l2)).
Code Snippet:
d = dict(zip(keys, values))Create a temporary file.
Experiencetempfile module.
Comprehensive Answer:
tempfile module.
Code Snippet:
import tempfile
with tempfile.NamedTemporaryFile() as t: ...Check for anagrams.
BeginnerSort and compare.
Comprehensive Answer:
Sort and compare.
Code Snippet:
sorted(s1) == sorted(s2)Find the GCD of two numbers.
Beginnermath.gcd().
Comprehensive Answer:
math.gcd().
Code Snippet:
import math
math.gcd(10, 20)Convert integer to binary string.
Beginnerbin().
Comprehensive Answer:
bin().
Code Snippet:
bin(10)Implement a simple timer class.
ExperienceContext manager.
Comprehensive Answer:
Context manager.
Code Snippet:
class Timer:
def __enter__(self): self.start = time.time(); return self
def __exit__(self, *a): print(time.time() - self.start)Sort list using custom comparator.
Experiencefunctools.cmp_to_key.
Comprehensive Answer:
functools.cmp_to_key.
Code Snippet:
sorted(l, key=cmp_to_key(my_cmp))Get memory usage of an object.
Experiencesys.getsizeof().
Comprehensive Answer:
sys.getsizeof().
Code Snippet:
import sys
sys.getsizeof(obj)How to capture stdout.
Experiencecontextlib.redirect_stdout.
Comprehensive Answer:
contextlib.redirect_stdout.
Code Snippet:
with redirect_stdout(f): print('hello')Parse JSON string.
Beginnerjson.loads().
Comprehensive Answer:
json.loads().
Code Snippet:
import json
data = json.loads(s)Check if file exists.
Beginneros.path.exists().
Comprehensive Answer:
os.path.exists().
Code Snippet:
os.path.exists('path')Simple async function loop.
Experienceasync for.
Comprehensive Answer:
async for.
Code Snippet:
async for item in async_gen(): print(item)Check if string starts with prefix.
Beginnerstartswith().
Comprehensive Answer:
startswith().
Code Snippet:
s.startswith('pre')