Python Interview Questions

Змішаний

Master Python programming with these essential interview questions covering data structures, OOP, decorators, generators, and more.

15 питань|
5 легко
5 середньо
5 складно

Lists are mutable (can be modified after creation) while tuples are immutable (cannot be changed). Lists use square brackets [] and tuples use parentheses (). Tuples are slightly faster and use less memory, making them ideal for fixed data. Lists are preferred when you need to add, remove, or modify elements.

data-structuresbasics

Decorators are functions that modify the behavior of other functions or classes without changing their source code. They use the @decorator syntax and work by wrapping the target function inside another function. Common use cases include logging, authentication, caching, and input validation.

decoratorsfunctions

A shallow copy creates a new object but references the same nested objects as the original, so changes to nested objects affect both copies. A deep copy creates a completely independent clone where all nested objects are also duplicated. Use copy.copy() for shallow copies and copy.deepcopy() for deep copies.

data-structuresmemory

Generators are functions that use the yield keyword to produce a sequence of values lazily, one at a time, instead of computing and storing them all in memory. They are memory-efficient for large datasets because they only generate values on demand. Each call to next() resumes execution from where the last yield paused.

generatorsperformance

The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time, even on multi-core systems. This means CPU-bound multi-threaded programs do not achieve true parallelism. To bypass the GIL, you can use multiprocessing, C extensions, or alternative interpreters like PyPy. I/O-bound threads still benefit from threading because the GIL is released during I/O operations.

concurrencyinternals

__str__ returns a human-readable string representation intended for end users, while __repr__ returns an unambiguous string representation intended for developers and debugging. If __str__ is not defined, Python falls back to __repr__. A good __repr__ should ideally return a string that could recreate the object.

oopmagic-methods

Python primarily uses reference counting, where each object tracks how many references point to it and is deallocated when the count reaches zero. To handle circular references that reference counting cannot resolve, Python also employs a cyclic garbage collector that periodically detects and cleans up reference cycles. The gc module allows manual control over the garbage collection process.

memoryinternals

*args allows a function to accept any number of positional arguments as a tuple, while **kwargs accepts any number of keyword arguments as a dictionary. They provide flexibility when the exact number of arguments is unknown. You can use them together in a function definition, but *args must come before **kwargs.

functionsbasics

A classmethod receives the class itself as its first argument (cls) and can access or modify class state, while a staticmethod receives no implicit first argument and behaves like a regular function scoped within the class. Classmethods are commonly used as alternative constructors. Staticmethods are used for utility functions that logically belong to the class but do not need access to class or instance data.

oopmethods

Python dictionaries use open addressing with a probing sequence to handle hash collisions. When two keys hash to the same slot, Python probes subsequent slots using a perturbation scheme until an empty one is found. This approach keeps all data in a single contiguous array, which is cache-friendly and efficient. As of Python 3.7+, dictionaries also maintain insertion order.

data-structuresinternals

List comprehensions are a concise syntax for creating lists by applying an expression to each item in an iterable, optionally with a filter condition. They are generally faster than equivalent for-loop constructions because they are optimized at the bytecode level. Use them for simple transformations and filtering, but prefer regular loops when the logic is complex or spans multiple lines for readability.

data-structuressyntax

MRO defines the order in which Python searches for methods in a class hierarchy, especially with multiple inheritance. Python uses the C3 linearization algorithm, which ensures that each class appears only once and that subclasses are checked before their parent classes. You can inspect the MRO using ClassName.__mro__ or ClassName.mro().

oopinheritance

The == operator checks for value equality, comparing whether two objects have the same content. The is operator checks for identity, verifying whether two references point to the exact same object in memory. For example, two different lists with identical contents will return True for == but False for is.

basicsoperators

Context managers are objects that define __enter__ and __exit__ methods to manage setup and teardown of resources automatically. The with statement ensures that cleanup code runs even if an exception occurs, making it ideal for file handling, database connections, and locks. You can create custom context managers using classes or the contextlib.contextmanager decorator with a generator function.

resource-managementpatterns

Metaclasses are classes whose instances are themselves classes, effectively controlling how classes are created and behave. The default metaclass is type, but you can define custom metaclasses by inheriting from type and overriding __new__ or __init__. They are used in frameworks like Django and SQLAlchemy to implement declarative APIs, automatic registration, and validation of class definitions.

oopadvanced