0% found this document useful (0 votes)
2 views6 pages

50 Python Qa

The document presents 50 Python interview questions categorized into topics such as Basics & Data Types, Data Structures, OOP Concepts, Functions, Scope & Error Handling, Iterators, Generators & Decorators, and Memory, Performance & Misc. Each question is accompanied by a concise answer, providing essential knowledge for candidates preparing for technical interviews. The content emphasizes understanding key concepts and best practices in Python programming.

Uploaded by

praveenvijay1357
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

50 Python Qa

The document presents 50 Python interview questions categorized into topics such as Basics & Data Types, Data Structures, OOP Concepts, Functions, Scope & Error Handling, Iterators, Generators & Decorators, and Memory, Performance & Misc. Each question is accompanied by a concise answer, providing essential knowledge for candidates preparing for technical interviews. The content emphasizes understanding key concepts and best practices in Python programming.

Uploaded by

praveenvijay1357
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

50 Python Questions

The Ones That Actually Get Asked in Interviews

If you can answer most of these confidently, you're genuinely interview-ready. If you can't, now you
know exactly what to go learn.

Basics & Data Types (8)

Q1. What is the difference between a list and a tuple?


A list is mutable — you can add, remove, or change elements after creation. A tuple is immutable — once created,
its contents can't be changed. Because tuples are immutable, they're faster to iterate over and can be used as
dictionary keys, while lists cannot.

Q2. What is the difference between '==' and 'is' in Python?


'==' checks if two objects have the same value. 'is' checks if two variables point to the exact same object in memory.
Two different lists with identical contents will be '==' equal but 'is' False, since they're separate objects in memory.

Q3. What are mutable and immutable data types in Python?


Mutable types can be changed after creation — lists, dictionaries, and sets. Immutable types cannot be changed
after creation — integers, strings, tuples, and frozensets. This distinction matters for function arguments, since
mutable objects can be modified inside a function and the change persists outside it.

Q4. What is the difference between deep copy and shallow copy?
A shallow copy creates a new object but inserts references to the same nested objects found in the original —
changing a nested list in the copy affects the original too. A deep copy recursively copies every nested object, so
the copy is fully independent. Use [Link]() when you need complete independence.

Q5. How does Python handle integer and float division differently?
The '/' operator always returns a float, even when dividing two integers evenly (5/2 gives 2.5). The '//' operator
performs floor division, returning the largest integer less than or equal to the result (5//2 gives 2). This trips up
beginners expecting '/' to behave like integer division in other languages.

Q6. What is the difference between 'is None' and '== None'?
'is None' checks identity — it confirms the object is literally the singleton None object, which is the recommended
and safe way to check. '== None' checks equality, which can technically be overridden by a custom class's __eq__
method to return True even for non-None objects, making it less reliable.

Q7. What are Python's built-in data types?


The core built-in types are: numeric (int, float, complex), sequence (list, tuple, range), text (str), mapping (dict), set
types (set, frozenset), and boolean (bool). Interviewers often ask this to check if you understand which category a
type falls into, since that affects mutability and behavior.

Q8. What is string interning in Python?


String interning is when Python reuses the memory of identical string literals instead of creating duplicates, mainly
for short strings and identifiers. This is why two identical short string literals can return True for 'is' comparison,
while longer or dynamically created strings usually don't.
Data Structures (8)

Q1. What is a dictionary and how does it store data internally?


A dictionary stores data as key-value pairs using a hash table internally. Each key is hashed to determine where its
value is stored, which is why dictionary lookups are close to O(1) on average, much faster than searching a list.

Q2. What is the difference between a set and a list?


A set stores only unique, unordered elements and offers fast O(1) average membership checks using hashing. A
list allows duplicates, maintains order, and membership checks are O(n) since it has to scan through elements. Use
a set when you need to remove duplicates or check existence quickly.

Q3. How do you remove duplicates from a list?


The simplest way is converting the list to a set and back to a list: list(set(my_list)). This removes duplicates but
doesn't preserve order. To preserve order, use [Link](my_list), since dictionaries maintain insertion order in
modern Python.

Q4. What is list comprehension and why is it preferred?


List comprehension is a concise way to build a list in a single line, like [x*2 for x in range(10)]. It's preferred over
traditional for-loops because it's more readable and generally faster, since it's optimized internally by Python's
interpreter.

Q5. What is the difference between append() and extend() in lists?


append() adds a single element to the end of a list, even if that element is itself a list (it gets nested). extend() adds
each element of an iterable individually to the list, flattening it in rather than nesting it.

Q6. How does slicing work in Python?


Slicing uses the syntax list[start:stop:step] to extract a portion of a sequence without modifying the original. The
start index is inclusive, the stop index is exclusive, and a negative step reverses the direction — list[::-1] reverses a
list entirely.

Q7. What is a frozenset?


A frozenset is an immutable version of a set — once created, elements can't be added or removed. Because it's
immutable and hashable, it can be used as a dictionary key or added to another set, unlike a regular set.

Q8. What is the time complexity of common dictionary operations?


Lookups, insertions, and deletions in a dictionary are O(1) on average, thanks to hashing. In the worst case (many
hash collisions), this can degrade to O(n), but in practice Python's implementation keeps this extremely rare.

OOP Concepts (10)

Q1. What are the four pillars of OOP and how does Python implement them?
Encapsulation (bundling data and methods, using naming conventions like _ and __ for privacy), Abstraction (hiding
implementation details behind simple interfaces), Inheritance (a class reusing behavior from a parent class), and
Polymorphism (the same method behaving differently depending on the object calling it).

Q2. What is the difference between a class method, static method, and instance method?
An instance method takes 'self' and can access/modify instance-specific data. A class method takes 'cls' instead
and can access/modify class-level data, shared across all instances. A static method takes neither — it's just a
regular function grouped inside a class for organizational purposes, with no access to instance or class state.

Q3. What is method overriding vs method overloading?


Method overriding is when a child class redefines a method already defined in its parent class, changing its
behavior. Python doesn't support traditional method overloading (same method name, different parameter counts)
like Java does — instead, default arguments or *args/**kwargs are used to achieve similar flexibility.

Q4. What is the difference between __init__ and __new__?


__new__ is responsible for actually creating a new instance of a class and is called first; it returns the object.
__init__ is called right after, and it initializes that already-created object with attribute values. __new__ is rarely
overridden except in advanced cases like singletons or immutable types.

Q5. What is multiple inheritance and how does Python resolve conflicts?
Multiple inheritance is when a class inherits from more than one parent class. Python resolves method conflicts
using the Method Resolution Order (MRO), following the C3 linearization algorithm, which you can inspect using
ClassName.__mro__.

Q6. What is the difference between an abstract class and a regular class?
An abstract class (defined using the ABC module) cannot be instantiated directly and is meant to be subclassed. It
can define abstract methods that must be implemented by any child class, enforcing a consistent interface across
subclasses.

Q7. What are dunder (magic) methods and why are they useful?
Dunder methods like __str__, __len__, and __eq__ let your custom classes integrate naturally with Python's built-in
syntax and functions. For example, defining __len__ lets you call len() on your own object, and __eq__ lets you
customize how '==' behaves for it.

Q8. What is the difference between composition and inheritance?


Inheritance models an 'is-a' relationship — a Dog is an Animal. Composition models a 'has-a' relationship — a Car
has an Engine, built by including an instance of one class inside another. Composition is often preferred for
flexibility, since it avoids tightly coupling classes through inheritance chains.

Q9. What is a property decorator (@property) used for?


The @property decorator lets you define a method that behaves like an attribute — you can call it without
parentheses. It's commonly used to add validation logic or computed values while keeping the clean syntax of direct
attribute access.

Q10. What is name mangling in Python (the double underscore prefix)?


When you prefix an attribute with double underscores (like __value), Python internally renames it to
_ClassName__value. This is Python's way of discouraging accidental access or overriding from subclasses, though
it's not true enforced privacy like in other languages.

Functions, Scope & Error Handling (8)

Q1. What is the difference between *args and **kwargs?


*args lets a function accept any number of positional arguments, collected into a tuple. **kwargs lets a function
accept any number of keyword arguments, collected into a dictionary. Both let you write flexible functions without
fixing the exact number of parameters in advance.

Q2. What is a lambda function and when would you use one?
A lambda is a small, anonymous, single-expression function, written as lambda x: x*2. It's typically used for short
operations passed directly into functions like map(), filter(), or sorted(), where defining a full named function would
be unnecessarily verbose.

Q3. What is variable scope in Python (local, global, enclosing)?


Local scope is inside the current function. Enclosing scope is any outer function it's nested within. Global scope is
the top level of the module. Python looks up variables in that order (Local → Enclosing → Global → Built-in), known
as the LEGB rule.

Q4. What is the difference between 'global' and 'nonlocal' keywords?


'global' lets a function modify a variable defined at the module's global scope. 'nonlocal' lets a nested function
modify a variable from its immediate enclosing function's scope, without making it fully global. Without either,
assigning to a variable inside a function creates a new local variable instead.

Q5. What happens with mutable default arguments in functions?


A common bug: using a mutable object (like a list) as a default argument causes it to be created only once, and
shared across all calls to that function, leading to unexpected accumulation of data. The fix is to default to None and
create the mutable object inside the function body.

Q6. What is exception handling and how does try-except-finally work?


try contains code that might raise an error. except catches and handles specific exception types if they occur. finally
runs regardless of whether an exception occurred, commonly used for cleanup like closing files or connections.

Q7. What is the difference between an error and an exception?


An error typically refers to a serious problem the program usually can't recover from (like a SyntaxError before the
program even runs). An exception is a runtime issue that can be caught and handled gracefully using try-except,
allowing the program to continue.

Q8. What is a custom exception and how do you create one?


A custom exception is created by defining a new class that inherits from Python's built-in Exception class. This lets
you raise and catch application-specific errors (like InvalidUserInputError) that communicate intent more clearly
than generic exceptions.

Iterators, Generators & Decorators (8)

Q1. What is the difference between an iterable and an iterator?


An iterable is any object you can loop over (like a list), implementing __iter__(). An iterator is the object returned by
calling iter() on an iterable, which implements __next__() to produce one value at a time. Every iterator is iterable,
but not every iterable is itself an iterator.

Q2. What is a generator and how is it different from a normal function?


A generator is a function that uses 'yield' instead of 'return', producing values one at a time and pausing its state
between calls, instead of computing and returning everything at once. This makes generators memory-efficient for
large or infinite sequences, since values are produced lazily.

Q3. What is the advantage of using a generator over a list?


A generator doesn't store all values in memory at once — it computes each value on demand. This is a major
advantage when working with very large datasets or infinite sequences, where building a full list upfront would
consume too much memory.

Q4. What is a decorator in Python?


A decorator is a function that wraps another function to extend or modify its behavior without changing its actual
code, using the @decorator_name syntax. Common uses include logging, timing execution, authentication checks,
and caching.

Q5. What is the difference between yield and return?


'return' exits a function immediately and sends back a single final value. 'yield' pauses the function, sends back a
value, and resumes exactly where it left off the next time it's called, maintaining its internal state across multiple
calls.

Q6. What is a context manager and what does the 'with' statement do?
A context manager handles setup and teardown logic automatically, most commonly for resource management like
file handling. The 'with' statement ensures __enter__() runs at the start and __exit__() runs at the end, even if an
error occurs — this is why 'with open(file) as f' automatically closes the file.

Q7. What is the difference between map(), filter(), and reduce()?


map() applies a function to every item in an iterable and returns transformed values. filter() applies a function that
returns True/False, keeping only items that pass. reduce() (from functools) combines all items into a single
cumulative value, like summing a list step by step.

Q8. What are *args and **kwargs used for in decorators specifically?
Since a decorator wraps a function without knowing its exact signature in advance, the inner wrapper function uses
*args and **kwargs to accept and forward any combination of arguments to the original function, making the
decorator reusable across different functions.

Memory, Performance & Misc (8)

Q1. What is the Global Interpreter Lock (GIL)?


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 multi-threading doesn't speed up CPU-bound tasks in Python, though it doesn't
affect I/O-bound tasks much, since the GIL is released during I/O waits.

Q2. What is the difference between multithreading and multiprocessing in Python?


Multithreading runs multiple threads within a single process, but the GIL limits true parallel execution for
CPU-bound work. Multiprocessing runs separate processes, each with its own Python interpreter and memory
space, genuinely achieving parallelism — better suited for CPU-heavy tasks.

Q3. How does Python manage memory?


Python uses automatic memory management through reference counting — an object is deallocated when its
reference count drops to zero. It also has a cyclic garbage collector to catch reference cycles (objects referencing
each other) that reference counting alone can't clean up.

Q4. What is the difference between shallow and deep understanding of Python's
pass-by-object-reference?
Python passes references to objects into functions, not copies. For mutable objects (lists, dicts), changes made
inside the function persist outside it. For immutable objects (int, str, tuple), reassigning inside the function just
creates a new local object, leaving the original untouched.

Q5. What is monkey patching?


Monkey patching means dynamically modifying or extending a class or module at runtime, without touching its
original source code. It's powerful for testing (mocking a function temporarily) but risky in production, since it can
create hard-to-trace bugs.

Q6. What is the difference between compiled and interpreted execution in Python?
Python source code is first compiled into bytecode (.pyc), and that bytecode is then interpreted by the Python
Virtual Machine (PVM) at runtime. This makes Python technically both compiled and interpreted, rather than purely
one or the other.
Q7. What is PEP 8 and why does it matter in interviews?
PEP 8 is Python's official style guide, covering naming conventions, indentation, and code layout. Interviewers
sometimes check if you follow it because consistent, readable code is a strong signal of real-world coding discipline,
not just problem-solving ability.

Q8. What is the difference between a module and a package?


A module is a single Python file containing functions, classes, or variables. A package is a directory containing
multiple modules, along with an __init__.py file that marks it as a package, allowing related modules to be
organized and imported together.

Made for students prepping for coding interviews — follow for more resources.

You might also like