Python Interview question
1. List, string, tuple, dictionary operation
1. List Operations
Creation: my_list = [1, 2, 3, 4]
Indexing: my_list[0] # 1
Slicing: my_list[1:3] # [2, 3]
Append: my_list.append(5)
Insert: my_list.insert(2, 99)
Extend: my_list.extend([6, 7])
Remove: my_list.remove(2) (removes first occurrence)
Pop: my_list.pop() # removes last element
Sort: my_list.sort()
Reverse: my_list.reverse()
Membership: 3 in my_list # True
Length: len(my_list)
2. String Operations
Creation: s = "Hello World"
Indexing: s[0] # 'H'
Slicing: s[0:5] # 'Hello'
Concatenation: "Hello" + "Python"
Repetition: "Hi" * 3 # 'HiHiHi'
Split: s.split() # ['Hello', 'World']
Join: ' '.join(['Hello', 'World'])
Find: s.find('World') # 6
Replace: s.replace('World', 'Python')
Case Conversion: s.upper(), s.lower(), s.title()
Strip: " text ".strip() # 'text'
Membership: 'H' in s # True
Length: len(s)
3. Tuple Operations
Creation: t = (1, 2, 3, 4)
Indexing: t[0] # 1
Slicing: t[1:3] # (2, 3)
Concatenation: (1, 2) + (3, 4)
Repetition: (1, 2) * 2 # (1, 2, 1, 2)
Membership: 2 in t # True
Length: len(t)
Count: t.count(2)
Index: t.index(3)
(Note: Tuples are immutable, so no append, remove, or sort.)
4. Dictionary Operations
Creation: d = {"name": "Suraj", "age": 22}
Access: d["name"] # 'Suraj'
Get with default: d.get("gender", "N/A")
Add/Update: d["city"] = "Mumbai"
Delete: del d["age"]
Pop: d.pop("name")
Popitem: d.popitem() (removes last item)
Keys: d.keys()
Values: d.values()
Items: d.items()
Membership: "name" in d # True
Length: len(d)
Clear: d.clear()
2. How Python memory management
In python memory management is handled automatically
All object is stored in a private heap space and python memory manager
takes care of allocation and deallocation
The primary mechanism is reference counting -> when an object
reference count drops to zero, it gets deallocated
However, since reference counting alone cannot handle circular
references, python also has a built-in garbage collector that detects and
clears cycles.
Python uses techniques like interning of small integers and strings, and
a special allocator called pymalloc for small objects.
As developers, we don’t need to manage memory manually, but we can
optimize usage by deleting unnecessary references, using generators for
large data and modules like numpy for memory- efficient computations.
3. What is in interning
Interning in python is an optimization technique where identical
immutable objects, mainly small integers and strings, are stored in a
shared memory pool instead of creating new objects every time.
For ex.
o Integers from -5 to 256 are pre-allocated and reused, and some
strings are also interned
o This saves memory and makes comparisons faster because Python
can just compare object references instead of values.
4. What is Object-Oriented Programming (OOP)?
OPPs is a programming paradigm based on the concept of objects.
These object bundle data and behavior together, making code more modular, reusable and easier to
maintain.
OOPs focuses on real-world modeling using classes and objects and it relies on four main
principles: encapsulation, inheritance, polymorphism and abstraction
5. What are the four main pillars of OOP?
The four main pillars of OOP are:
Encapsulation Wrapping data and method into single unit and controlling assess using access
modifiers
Inheritance Creating new classes from existing ones to promote code reuse and hierarchy
Polymorphism Ability of same function or operator to behave differently based on context
Abstraction Hiding implementation details and exposing only essential features, usually via
abstract classes or interfaces.
6. Difference between a class and an object.
Aspect Class Object
A blueprint or template that defines attributes An instance of a class created in
Definition
(data) and methods (behavior). memory.
Nature Logical entity. Physical entity (exists in memory).
Created many times from a class using
Creation Defined once using the class keyword.
the constructor.
Does not occupy memory until objects are
Memory Occupies memory when instantiated.
created.
Used to access and manipulate actual
Usage Used to define structure and behavior.
data and behavior.
Example class Car: pass my_car = Car()
(Python)
Yes, you can create an empty class without pass by using ellipsis (...) instead.
o class MyClass: ...
This works the same way as using pass, keeping the class body syntactically valid but empty.
7. What is __init__ in Python?
__init__ in python is a special method called the constructor.
It is automatically invoked when an object of a class is created.
Its main purpose is to initialize the object’s attributes with default or passed values.
__init__ is not mandatory; if absent, Python uses a default constructor.
It’s similar to constructors in Java/C++, but Python allows multiple ways of handling initialization.
Python doesn’t support true multiple constructors, but we can mimic it using default arguments or
class methods.
8. What are the multiple ways of handling initialization.
Python does not support multiple constructor directly like java or c++, but we can handle different
initialization requirements in several ways:
default Argument __init__
variable Arguments (*args,**kwargs)
Class Method as Alternative Constructors
* use @classmethod to define multiple named constructors.
Factory Functions (outside the class)
9. what are *args and **kwargs
"In Python, *args and **kwargs are used in function definitions to pass a variable number of
arguments.
*args (Non-Keyword Arguments): Collects extra positional arguments as a tuple.
**kwargs (Keyword Arguments): Collects extra keyword arguments as a dictionary.
*args Handles variable number of positional arguments (stored as tuple)
**kwargs handles variable number of keyword arguments (stored as dict)
10. Can Python have multiple constructors?
Unlike Java or C++, Python does not support multiple constructors directly. A class can
only have one __init__ method, and if you define another, it will overwrite the previous
one.
11. What is the difference between procedural and object-oriented programming?
Aspect Procedural Programming (PP) Object-Oriented Programming (OOP)
Programming paradigm based on Programming paradigm based on objects (data
Definition
procedures (functions). + behavior together).
Focuses on functions that operate on Focuses on objects that encapsulate data and
Focus
data. methods.
Data is often global and shared Data is encapsulated within objects, restricting
Data Handling
across functions. direct access.
Code reuse via inheritance and
Reusability Code reuse via functions.
polymorphism.
Less secure, as functions can directly More secure due to encapsulation and access
Security
access global data. control.
Example
C (mainly procedural). Java, Python, C++, etc. (support OOP).
Language
Example Functions like def add(a,b): Classes like class Calculator: def
(Python) return a+b. add(self,a,b): return a+b.
12. Can Python support multiple constructors?
Unlike Java or C++, python does not support multiple constructors directly. A class can have one
__init__ method, and if you define another, it will overwrite the previous one
Difference between instance variables and class variables.
Aspect Instance Variable Class Variable
Belongs to a specific object (instance) of the
Definition Shared across all objects of the class.
class.
Defined inside __init__ (or other methods) Defined directly inside the class, outside any
Declaration
using self. method.
Storage Each object has its own copy. Stored only once at the class level.
Accessed via Class.class_var or
Access Accessed via object.instance_var.
object.class_var.
Modification Changing in one object doesn’t affect others. Changing via class name affects all objects.
Use Case Store data unique to each object. Store data common to all objects.
13. What is self in Python?
In python, self refers to the instance of the class that is being operated on.
It automatically passed as the first parameter to instance methods.
When you create an object from a class, self allows the object to access its own variables and
method
It differentiates instance variables from local variables.
self must be the first parameter in instance methods, but you don’t pass it explicitly when
calling the method.
It represents the current object.
Without self, Python wouldn’t know whether you are referring to a class variable, a local
variable, or an instance variable.
14. which oops concepts are not supported in python that are supports in mostly oops oriented language
OOP Concepts Supported in Python
Encapsulation (via classes and private variables _var or __var)
Inheritance (single, multiple, multilevel, hierarchical, hybrid)
Polymorphism (method overriding, operator overloading)
Abstraction (using abc module with abstract base classes)
OOP Concepts Not Strictly Supported in Python
1. Access Modifiers (private, protected, public)
o In Java/C++, you have keywords: public, private, protected.
o In Python, there are no strict access modifiers. Instead:
_var → weak convention for protected (just a warning, still accessible).
__var → name mangling (harder to access but still possible).
o So, encapsulation is not enforced, only followed by convention.
2. Method Overloading
o In Java/C++, you can define multiple methods with the same name but different parameter
lists.
o In Python, the last defined method overwrites the previous one.
o Alternative → Achieved with default arguments or *args/**kwargs.
3. True Compile-Time Polymorphism
o Python is dynamically typed, so overloading and static binding (like in C++/Java) are not
truly present.
o Only runtime polymorphism (method overriding, duck typing) is supported.
4. Strict Data Hiding
o In C++/Java, private variables are truly private.
o In Python, “private” variables can still be accessed using tricks (e.g., _ClassName__var).
5. Interfaces
o Java/C++ has explicit interface keywords.
o Python doesn’t have them, but it uses abstract base classes (ABC) as a workaround.
15. Difference between is and == in Python.
Feature is ==
Meaning Checks identity → whether two references Checks equality → whether the values of
Feature is ==
point to the same object in memory two objects are the same
Comparison
Compares object IDs Compares data/contents
Type
True only if both variables refer to the True if the values stored in objects are
When True
exact same object equal, even if they are different objects
Often used for checking None or singleton Used for value comparisons like numbers,
Usage
objects strings, lists, etc.
Example a is b a == b
16. What are dunder/magic methods in Python?
Dunder methods are special methods in Python with double underscores that let us define or
customize how objects behave with built-in functions and operators.
Examples:
__init__ → Constructor, called when object is created.
__str__ → Defines string representation (print(obj)).
__len__ → Defines behavior of len(obj).
__eq__ → Defines behavior of ==.
__add__ → Defines behavior of + operator.
17. What is encapsulation in OOP?
Encapsulation is the process of bundling data (variables) and methods (functions) that operate on
that data into a single unit (class), while also controlling access to them.
Purpose:
Protects data from direct modification.
Provides controlled access using getters and setters.
Improves security, maintainability, and flexibility.
How in Python:
Public: var → accessible anywhere.
Protected: _var → convention (shouldn’t be accessed outside class).
Private: __var → name mangling (harder to access).
18. How do you achieve encapsulation in Python?
Using access specifiers (by convention)
Public (var) → Accessible everywhere.
Protected (_var) → Intended for internal use (not enforced).
Private (__var) → Name mangling makes it harder to access outside the class.
Using Getters and Setters
Provide controlled access to private variables through methods.
Using @property Decorator
Pythonic way to achieve encapsulation → allows attribute access while internally calling
getter/setter.
20. Difference between public, protected, and private members in Python.
Type Syntax Access Level Usage in Python
Accessible from anywhere (inside & outside the Default behavior, no
Public var
class) restrictions
Accessible within the class and subclasses, but
Protected _var Just a convention, not enforced
treated as "internal use only"
Accessible only within the class (name mangling: Stronger restriction but can still
Private __var
_ClassName__var) be bypassed
21. Can private variables be accessed outside the class in Python?
By definition, private variables in Python are created using __var (double underscore).
Python performs name mangling → it internally renames __var to _ClassName__var.
This makes direct access difficult, but not impossible.
21. What is inheritance and why is it useful?
Inheritance is an OOP concept where a class (child/derived) can reuse the attributes and
methods of another class (parent/base).
It allows code reusability, extensibility, and maintainability.
Why is Inheritance Useful?
1. Code Reusability → Common code written once in the parent class can be reused in child classes.
2. Extensibility → Child classes can add new features without modifying existing parent code.
3. Maintainability → Centralized logic (e.g., in parent) makes changes easier.
4. Polymorphism Support → Enables method overriding and dynamic behavior.
5. Hierarchical Organization → Helps model real-world relationships (e.g., Animal → Dog, Cat).
22. Types of inheritance in Python (single, multiple, multilevel, hierarchical, hybrid).
Type Description Example
Single A child class inherits from one parent class. class Dog(Animal): ...
A child class inherits from multiple parent class SmartPhone(Phone,
Multiple Camera): ...
classes.
Inheritance in a chain (grandparent → parent → class Puppy(Dog): ...
Multilevel
child).
Multiple child classes inherit from the same class Dog(Animal), class
Hierarchical Cat(Animal)
parent.
Hybrid Combination of two or more types of inheritance. Mix of multiple + multilevel
Python supports five types of inheritance: single, multiple, multilevel, hierarchical, and hybrid,
allowing us to model real-world relationships and maximize code reusability.
What is method overriding? Give an example.
Method overriding occurs when a child class defines a method with the same name and parameters
as a method in its parent class, but provides a different implementation.
Key Points:
Achieved during inheritance.
Allows a child class to customize or extend the behavior of the parent class method.
Supports runtime polymorphism.
23. How do you call the parent class constructor in Python?
There are two ways to call the parent class constructor:
1. Using super() (preferred)
o Calls the parent constructor automatically following the MRO (Method Resolution
Order).
o Cleaner and works well with multiple inheritance.
2. Using Parent Class Name directly
o Explicitly calls the parent constructor.
o Not recommended in multiple inheritance (can cause duplicate calls).
In Python, the parent class constructor can be called using super().__init__() (preferred for
multiple inheritance) or by explicitly calling ParentClass.__init__(self, ...)
24. Can Python support multiple inheritance? How does it resolve conflicts?
Yes, Python supports multiple inheritance, and it resolves conflicts using the Method Resolution
Order (MRO), which follows the C3 linearization algorithm
25. What is polymorphism in OOP?
Polymorphism means "many forms".
Ability of same function or operator to behave differently based on context
Why Useful:
o Improves flexibility and reusability.
o Supports dynamic behavior at runtime.
o Helps write cleaner, extensible code.
Types of Polymorphism in Python
1. Method Overriding (Runtime Polymorphism)
o A child class provides a new implementation of a parent class method.
2. Method Overloading (Compile-Time Polymorphism)
o Python doesn’t support it directly, but it can be achieved using default arguments, *args,
or @singledispatch.
3. Operator Overloading
o Defining custom behavior for operators using dunder methods (__add__, __eq__, etc.).
4. Duck Typing
o "If it walks like a duck and quacks like a duck, it’s a duck." → Object behavior matters
more than type.
26. What is the difference between overloading and overriding?
Feature Overloading Overriding
Same method name, different Same method name & arguments, new definition
Definition
arguments in child
Occurs in Same class Parent–child relationship
Type Compile-time (in other languages) Runtime
Support in Not directly (use default args,
Fully supported
Python *args)
27. Does Python support method overloading?
In strict sense → No.
Unlike Java or C++, Python does not support method overloading by having multiple methods with the
same name but different signatures.
If you define the same method name multiple times, only the last definition is kept.
28. How do len() and + operator demonstrate polymorphism in Python?
Polymorphism means same function/operator behaves differently depending on the object type.
len() Function
The same built-in function len() works with different data types:
Polymorphism in action: One function (len) adapts to different types.
+ Operator
The same operator behaves differently depending on operand type:
Polymorphism in action: The + operator performs addition, concatenation, or merge based on
operand types
len() and + in Python demonstrate polymorphism because they perform different behaviors depending on
the object type, showing the concept of 'one interface, many implementations'."
29. Example of runtime polymorphism in Python.
Definition: Runtime polymorphism happens when the method to be executed is determined at runtime,
not at compile time.
In Python, this is mainly achieved using method overriding with inheritance.
30. What is abstraction in OOP?
Abstraction is the OOP concept of hiding implementation details and showing only the essential
features to the user.
Goal:
Focus on what an object does rather than how it does it.
How Abstraction is Achieved in Python
Python achieves abstraction using abstract classes and interfaces.
We use the abc module (Abstract Base Class).
Any class with at least one abstract method becomes abstract and cannot be instantiated.
31. How is abstraction implemented in Python?
32. What is the difference between abstract class and interface?
Feature Abstract Class Interface
A class that may contain abstract A contract that contains only abstract
Definition methods (no body) as well as concrete methods (in Python, abstract base classes
methods (with implementation). can simulate interfaces).
Method Can have both abstract and non-abstract Traditionally, only abstract methods (no
Implementation methods. implementation).
Feature Abstract Class Interface
Usually constants (in strict OOP
Can have instance variables and class
Variables languages). In Python, we simulate via
variables.
abstract base classes.
A class can inherit only one abstract A class can implement multiple
Inheritance
class (single inheritance). interfaces (multiple inheritance).
When classes share common code + must When classes share only a contract and
Use Case
enforce certain methods. no common code.
Instantiation Cannot be instantiated directly. Cannot be instantiated directly.
33. Can we instantiate an abstract class in Python?
Why do we need abstraction if encapsulation already hides data?
33. Python data type
. Numeric Types
int → Whole numbers (10, -25)
float → Decimal numbers (3.14, -0.99)
complex → Complex numbers (2 + 3j)
2. Sequence Types
str → Strings ("Hello", 'Python')
list → Ordered, mutable ([1, 2, 3])
tuple → Ordered, immutable ((1, 2, 3))
range → Sequence of numbers (range(5) → 0,1,2,3,4)
3. Mapping Type
dict → Key-value pairs ({"name": "Suraj", "age": 22})
4. Set Types
set → Unordered, unique elements ({1, 2, 3})
frozenset → Immutable set (frozenset({1, 2, 3}))
5. Boolean Type
bool → True / False
6. Binary Types
bytes → Immutable byte sequence (b"Hello")
bytearray → Mutable byte sequence (bytearray([65, 66, 67]))
memoryview → Memory view of byte objects (memoryview(b'XYZ'))
7. None Type
NoneType → Represents absence of value (None)
34. Mutable vs Immutable in Python
Mutable objects → Can be changed after creation (modify content without changing memory
reference).
Immutable objects → Cannot be changed after creation (any modification creates a new object
in memory).
Category Mutable Immutable
Numbers ❌ (no mutable numbers) int, float, complex
Sequence list, bytearray str, tuple, range, bytes
Mapping dict ❌
Set Types set frozenset
Boolean ❌ bool
Special ❌ NoneType (None)