0% found this document useful (0 votes)
4 views39 pages

Python Interviews Question

The document provides an extensive overview of Python, covering its features, data types, and key concepts such as virtual environments, PEP 8, and the differences between lists, tuples, sets, and dictionaries. It explains how Python interprets code, the differences between mutable and immutable types, and various programming constructs like functions, loops, and exception handling. Additionally, it discusses Python's memory management, keywords, and comparisons between Python 2 and Python 3.

Uploaded by

rashidaliii5012
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)
4 views39 pages

Python Interviews Question

The document provides an extensive overview of Python, covering its features, data types, and key concepts such as virtual environments, PEP 8, and the differences between lists, tuples, sets, and dictionaries. It explains how Python interprets code, the differences between mutable and immutable types, and various programming constructs like functions, loops, and exception handling. Additionally, it discusses Python's memory management, keywords, and comparisons between Python 2 and Python 3.

Uploaded by

rashidaliii5012
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

1. What is Python ? With it’s Features.

2. How to create Virtual environment ?


3. What is PEP8 ?
4. How does Python interpret code ? Explain interpreter vs Compiler .
5. What are python variables?
6. What are python data types ?
7. Difference between list, tuple, set, and dict.
8. What is the difference between == and is ?
9. What are mutable and immutable types?
10. Explain None, True, False
11. What are *args and **kwargs ?
12. Explain list comprehension with example.
13. What is slicing in python ?
14. How to swap two numbers without a temp variable ?
15. Difference between local and global variables.
16. How to import modules in python ?
17. What are built-in functions ?
18. Why Python Dynamically typed ?
19. How many Keyboards in Python ?
20. Python 2 VS Python 3 ?
21. How does memory management work in Python ?
22. How Many loops in python ?
23. What is module ? Any Difference between module and function.
24. How to handle exception in python ? (try / except)
25. Break VS Continue VS Pass ?
26. Explain the usage of anonymous dunction ?
27. How to perform Read / Write operation on file in python ?
28. What is OOPs in python ?
29. What is the purpose of the “ if name == ‘main’ ” condition in python scripts ?
30. What is this __init__() in python ?
31. What is inheritance ?
32. What is polymorphism ?
33. Difference between Overloading and overriding.
34. How we can perform “unit testing” in python ?
35. “ is ” VS “==” in python ?
36. Can we improve the performance of python code ? Ans : Yes / No
37. What is the use of range() ?
38. What is Operator ?
39. Explain Python Scope: LEGB rule
40. Explain functions, lambda , map , filter , reduce.
41. What are decorators in python ? And how to use them.
42. Generators & yield vs return.
43. Difference between deepcopy and shallowcopy.
44. What is duck typing ?
45. Explain Python memory allocation & garbage collection.
46. What are iterators and iterables ?
47. Explain comprehensions ( list , dict , set ) in depth.
48. Explain Type Hinting in python ?
49. What is Global interpreter Lock (GIL) ?
50. What is multithreading in python ?
51. Threading vs multiprocessing
52. Explain file handing and context managers ( With Keyword )
53. Explain Exception hierarchy and custom exceptions
54. Difference between class and object
55. Explain __init__, new_, and other dunders
56. Class methods vs static methods vs instance methods
57. Metod overloading vs overriding in python.
58. Explain properties and descriptors
59. What are modules and packages ? How to create and install ?

60. Explain function closures & closures with state


61. Explain how Python dictionaries are implemented
62. Internals of Python list resizing
63. Explain Python bytecode and dis module
64. Concurrency – sync va threads vs processes
65. Explain data model and special methods deeply
66. Implement iterator protocol manually
67. Explain memory leaks in python and how to debug
68. Explain introspection in python
69. Explain how class attributes and instance attributes ae resolved
70. Explain serialization & picking limitations
71. Explain different Python implementations ( CPython , PyPy, Jython , etc. )

Q1. What is Python? With its Features.

Python is an object-oriented, high-level, dynamic, and multipurpose programming


language.
Python supports multiple programming pattern, including object-oriented
programming, and functional programming, or procedural programming.

It is an interpreted language.

Features of Python:

1. Simple and easy to learn.

2. High-level programming language.

3. Interpreted language.

4. Dynamically typed.

5. Object-oriented programming support.

6. Free and open-source.

7. Platform independent.

8. Portable.

9. Rich standard library.

10. Extensible (can be extended using C/C++).

11. Embedded.

12. Suitable for rapid application development.

History of Python :-

It was created by Guido Van Rossum in Netherlands during 1989-1991.

Guido Van Rossum is fan of “Monty Python’s Flying Circus’ , this is a famous TV
comedy show in Netherlands, So that Named Python .

It is open sourced from the beginning.

Q. Difference Between Compiler and Interpreter

Compiler and interpreter are both called translators. They both convert high-level
language into low-level language. However, there are some major differences between
them. A compiler executes the whole program at a time, while an interpreter
executes the program line by line.
Python is a Interpreter Based Language.

Python interpreter name is CPYTHON.

Q2. How to create Virtual Environment?

Answer:

A Virtual Environment is an isolated Python environment that allows each project


to have its own packages and dependencies without affecting other projects.

Steps to create a Virtual Environment (Windows):

1. Open Command Prompt.

2. Move to your project folder.

Command: cd project_folder

3. Create a virtual environment.

Command: python -m venv myenv

4. Activate the virtual environment.

Command: myenv\Scripts\activate

5. Install the required packages.

Command: pip install package_name

6. To exit the virtual environment.

Command: deactivate

Q3. What is PEP 8?

Answer:

PEP 8 (Python Enhancement Proposal 8) is the official coding style guide for
Python. It provides rules and recommendations for writing clean, readable, and
consistent Python code.

PEP 8 Guidelines:

1. Use 4 spaces for indentation.


2. Use meaningful names for variables and functions.

3. Keep code properly formatted and readable.

4. Leave blank lines between functions and classes.

5. Write comments where necessary.

6. Follow standard naming conventions.

7. Keep line length within the recommended limit.

Q. What is the purpose of Set in Python?

A set is an unordered and mutable collection of unique elements. The main


purpose of a set is to store unique values, remove duplicate items, and
perform set operations such as union, intersection, difference, and symmetric
difference.

Key Points:

1. Stores only unique elements.

2. Automatically removes duplicate values.

3. Unordered collection (no indexing).

4. Mutable (elements can be added or removed).

5. Supports set operations like union, intersection, and difference.

Q4. How does Python interpret code? Explain Interpreter vs Compiler.

Answer:

Python is an interpreted language. When a Python program runs, the source code
is first converted into bytecode. The Python Virtual Machine (PVM) then executes
the bytecode line by line. This makes Python portable and easy to debug.

Difference between Interpreter and Compiler

Interpreter Compiler

Executes code line by line. Translates the entire program at once.

Stops when an error occurs. Reports errors after compilation.


Interpreter Compiler

Easier to debug. Faster execution after compilation.

No executable file is created. Creates an executable file.

Example: Python Example: C, C++

Q5. What are Python Variables?

Answer:

A variable is a name used to store data in memory. It acts like a container that holds
a value. In Python, you do not need to declare the data type of a variable because
Python automatically identifies it based on the assigned value.

Example:

name = "Rashid"

age = 22

salary = 25000.50

Python variables can store different types of data such as integers, floating-point
numbers, strings, lists, tuples, sets, and dictionaries.

Q6. What are Python Data Types?

Answer:

A data type specifies the type of value stored in a variable. Python automatically
identifies the data type based on the assigned value.

Common Python Data Types:

1. int – Integer numbers

2. float – Decimal numbers

3. str – Text values

4. bool – True or False

5. list – Ordered and mutable collection

6. tuple – Ordered and immutable collection

7. set – Unordered collection of unique elements


8. dict – Collection of key-value pairs

Q7. Difference between List, Tuple, Set, and Dictionary.

Answer:

Feature List Tuple Set Dictionary

Ordered Ordered Unordered Key-value


Definition
collection collection collection collection

Mutable Yes No Yes Yes

Yes (Python
Ordered Yes Yes No
3.7+)

Duplicate Duplicate keys


Allowed Allowed Not Allowed
Values not allowed

Indexing Yes Yes No Access by key

Syntax [] () {} {key: value}

a) List: A List is an ordered and mutable collection that allows duplicate values. It is
created using square brackets [ ].
b) Tuple: A Tuple is an ordered and immutable collection that allows duplicate
values. It is created using parentheses ( ).
c) Set: A Set is an unordered and mutable collection that stores only unique
values. Duplicate values are not allowed. It is created using curly braces { }.
d) Dictionary: A Dictionary is a mutable collection of key-value pairs. Keys must be
unique, while values can be duplicated. It is created using curly braces {key:
value}.

Q8. What is the difference between == and is?

Answer:

Both == and is are comparison operators, but they work differently.


== is

Compares the values of two Compares whether two variables refer to the same
objects. object in memory.

Returns True if values are Returns True only if both variables point to the
equal. same object.

Checks value equality. Checks object identity.

Example:

a = [1, 2]

b = [1, 2]

a == b → True

a is b → False

Q9. What are Mutable and Immutable Types?

Answer:

1. Mutable Types: Mutable objects can be changed or modified after they are
created without creating a new object.
Examples: List, Dictionary, Set.
2. Immutable Types: Immutable objects cannot be changed after they are created.
If you modify them, a new object is created instead.
Examples: Integer (int), Float (float), String (str), Tuple, Boolean (bool).

Q10. Explain None, True, False.

Answer:

None

• None represents the absence of a value.

• It is often used to indicate that a variable has no value assigned.

Example:

data = None

True

• True is a Boolean value that represents a true condition.


• It is commonly used in conditional statements and logical operations.

Example:

is_active = True

False

• False is a Boolean value that represents a false condition.

• It is used when a condition is not satisfied.

Example:

is_logged_in = False

True and False are Boolean values, while None represents no value or null.

Q11. What are *args and **kwargs?

Answer:

*args and **kwargs are used to pass a variable number of arguments to a function.

*args

• Used to pass multiple positional arguments.

• Arguments are stored as a tuple.

Example:

def add(*args):

return sum(args)

add(10, 20, 30)

**kwargs

• Used to pass multiple keyword arguments.

• Arguments are stored as a dictionary.

Example:

def student(**kwargs):

print(kwargs)

student(name="Ali", age=20)
Q12. Explain List Comprehension with Example.

Answer:

List Comprehension is a short and readable way to create a new list from an existing
iterable. It is commonly used to transform data, filter data, and create new
collections.

Syntax:

[expression for item in iterable if condition]

Example:

numbers = [1, 2, 3, 4, 5]

squares = [x * x for x in numbers]

Output:

[1, 4, 9, 16, 25]

Example with Condition:

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = [x for x in numbers if x % 2 == 0]

Output:

[2, 4, 6]

Q13. What is Slicing in Python?

Answer:

Slicing is used to access a part of a sequence such as a string, list, or tuple. It allows
you to extract a range of elements without modifying the original data.

Syntax:

sequence[start : stop : step]

Example:

name = "Python"

print(name[0:4])

Output:
Pyth

Example:

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

Output:

[20, 30, 40]

Q14. How to swap two numbers without a temp variable?

Answer:

In Python, two numbers can be swapped without using a temporary variable by


using multiple assignment.

Example:

a = 10

b = 20

a, b = b, a

print(a)

print(b)

Output:

20

10

Q15. Difference between Local and Global Variables.

Answer:

Local Variable Global Variable

Declared inside a function. Declared outside a function.

Can be used only inside that function. Can be used throughout the program.

Created when the function is called. Created when the program starts.
Local Variable Global Variable

Destroyed after the function ends. Exists until the program ends.

Q16. How to import modules in Python?

Answer:

A module is imported using the import keyword. Python provides different ways to
import modules.

Import Entire Module

import math

Import Specific Function

from math import sqrt

Import with Alias

import numpy as np

Import Multiple Functions

from math import sqrt, factorial

Q17. What are Built-in Functions?

Answer:

Built-in functions are predefined functions provided by Python. They can be used
directly without importing any module.

Common Built-in Functions:

• print() – Displays output.

• input() – Takes input from the user.

• type() – Returns the data type.

• len() – Returns the length of an object.

• sum() – Returns the sum of values.

• max() – Returns the largest value.

• min() – Returns the smallest value.


• round() – Rounds a number.

• sorted() – Sorts data.

• abs() – Returns the absolute value.

Q18. Why Python is Dynamically Typed?

Answer:

Python is called a dynamically typed language because you do not need to declare
the data type of a variable. Python automatically determines the data type based on
the value assigned to the variable.

Example:

x = 10

x = "Python"

x = 3.14

The same variable can store different types of values during program execution.

Q19. How many Keywords in Python?

Answer:

Python currently has 35 keywords (Python 3.10+).

Keywords are reserved words that have predefined meanings and cannot be used as
variable names, function names, or class names.

Examples:

False, None, True, and, as, assert, async, await, break, class, continue, def,
del, elif , else, except, finally, for, from, global, if, import, in, is, lambda,
nonlocal, not, or, pass, raise, return, try, while, with, yield.

Note: The number of keywords depends on the Python version. Older versions had
fewer keywords.

Q20. Python 2 vs Python 3.

Answer:
Python 2 Python 3

Released in 2000. Released in 2008.

No longer supported. Actively supported.

print is a statement. print() is a function.

input() behaves differently. input() always returns a string.

Better Unicode support is not


Full Unicode support is available.
available.

Includes many new features and


Fewer modern features.
improvements.

Not recommended for new


Recommended for all new projects.
projects.

Q21. How does memory management work in Python?

Answer:

Python automatically manages memory using private heap memory. Memory is


allocated by the Python Memory Manager, and unused objects are removed
automatically by the Garbage Collector, so programmers do not need to manage
memory manually.

Q22. How Many Loops in Python?

Answer:

Python has two types of loops:

1. for loop – Used to iterate over a sequence (list, tuple, string, dictionary, etc.).

2. while loop – Repeats a block of code while a condition is True.

Q23. What is Module? Any Difference between Module and Function.

Answer:
A module is a Python file (.py) that contains reusable code such as functions,
classes, and variables.

Module Function

A block of reusable code inside a


A file containing Python code.
module.

Can contain multiple functions, classes, and


Performs a specific task.
variables.

Imported using import. Called using its function name.

Q24. How to handle Exception in Python? (try / except)

Answer:

Exceptions are handled using the try and except blocks. The code that may cause
an error is placed inside the try block, and if an error occurs, it is handled by the
except block.

Example:

try:
num = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

Q25. Break VS Continue VS Pass?

Answer:

break continue pass

Skips the current iteration and


Terminates the loop Does nothing; it is a
continues with the next
immediately. placeholder statement.
iteration.

Q26. Explain the usage of Anonymous Function.

Answer:

An anonymous function is a function without a name. In Python, it is created using


the lambda keyword. It is mainly used for short functions that are used only once.
Example:

square = lambda x: x * x

print(square(5))

Output:

25

Q27. How to perform Read / Write operation on file in Python?

Answer:

Python uses the open() function to read and write files.

Read a File

Command: file = open("[Link]", "r")

Command: print([Link]())

Command: [Link]()

Write to a File

Command: file = open("[Link]", "w")

Command: [Link]("Hello Python")

Command: [Link]()

Q28. What is OOPs in Python?

Answer:

Object-Oriented Programming (OOP) is a programming approach that uses


classes and objects to organize code. It helps in writing reusable, secure, and
maintainable programs.

Main Principles of OOP:

1. Class

2. Object

3. Encapsulation

4. Inheritance

5. Polymorphism
6. Abstraction

Advantages of OOP

• Provides a clear structure to programs

• Makes code easier to maintain, reuse, and debug

• Helps keep your code DRY (Don't Repeat Yourself)

• Allows you to build reusable applications with less code

Q29. What is the purpose of the if __name__ == "__main__" condition in Python


scripts?

Answer:

The if __name__ == "__main__" statement checks whether a Python file is being run
directly or imported as a module.

• If the file is run directly, the code inside this block executes.

• If the file is imported into another program, the code inside this block does not
execute.

Example :

def greet():

print("Hello")

if __name__ == "__main__":

greet()

Output : Hello

Q30. What is __init__() in Python?

Answer:

__init__() is a constructor in Python. It is a special method that is automatically


called when an object of a class is created. It is used to initialize the object's
attributes.

Example:
class Student:

def __init__(self, name):

[Link] = name

s = Student("Ali")

print([Link])

Output : Ali

Q31. What is Inheritance?

Answer:

Inheritance allows us to define a class that inherits all the methods and properties
from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Example:

class Animal:
def sound(self):
print("Animal Sound")
class Dog(Animal):
pass
d = Dog()
[Link]()

Q32. What is Polymorphism?

Answer:

Polymorphism is an Object-Oriented Programming (OOP) feature that allows the


same method or function to perform different actions depending on the object.
The word Polymorphism means "many forms."

Example:

class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")

Dog().sound()
Cat().sound()
Output :

Bark

Meow

Q33. Difference between Overloading and Overriding.

Answer:

Method Overloading Method Overriding

Same method name with different Same method name and same
parameters. parameters in parent and child classes.

Python does not support true


Fully supported in Python.
method overloading directly.

Achieved using default or variable


Achieved using inheritance.
arguments.

Q34. How we can perform Unit Testing in Python?

Answer:

Unit testing is used to test individual functions or methods of a program. Python


provides the built-in unittest module for writing and running test cases.

Example:

import unittest

class Test([Link]):

def test_add(self):

[Link](2 + 3, 5)

[Link]()
Q35. "is" VS "==" in Python?

Answer:

== is

Compares values. Compares object identity (memory location).

Returns True if values are Returns True if both variables refer to the same
equal. object.

Q36. Can we improve the performance of Python code?

Yes.

Python code performance can be improved by:

1. Using efficient algorithms.

2. Using built-in functions.

3. Using list comprehensions.

4. Using generators for large data.

5. Using NumPy and Pandas for data processing.

6. Avoiding unnecessary loops.

7. Using multiprocessing for CPU-intensive tasks.

Q37. What is the use of range()?

Answer:

The range() function generates a sequence of numbers. It is mainly used with for
loops to repeat a block of code a specific number of times.

Example:

for i in range(1, 6):

print(i)

Output:

12345

Q38. What is Operator?


Answer:

Operators are symbols used to perform operations on values and variables.

They allow you to calculate, compare, assign, and combine data in different ways.

Types of Operators:

1. Arithmetic Operators: +, -, *, /, %, //, **


2. Comparison (Relational) Operators: ==, !=, >, <, >=, <=
3. Assignment Operators: =, +=, -=, *=, /=, %=, //=, **=
4. Logical Operators: and, or, not
5. Bitwise Operators: &, |, ^, ~, <<, >>
6. Membership Operators: in, not in
7. Identity Operators: is, is not

Q39. Explain Python Scope: LEGB Rule.

Answer:

The LEGB Rule defines the order in which Python searches for a variable.

• L – Local: Variables inside a function.

• E – Enclosing: Variables in the enclosing function.

• G – Global: Variables declared outside all functions.

• B – Built-in: Python's built-in names and functions.

Python searches variables in the order: Local → Enclosing → Global → Built-in.

Q40. Explain Functions, Lambda, Map, Filter, Reduce.

Answer:

Function

A function is a block of code which only runs when it is called.

A function can return data as a result.

A function helps avoiding code repetition.

Example:

def greet():

print("Hello")
Lambda

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one
expression.

Example:

add = lambda a: a + 10

print(add(5))

Map

The map() function is used to apply a function to each item of an iterable (such as
a list or tuple). It returns a map object, which can be converted into a list, tuple, etc.
Example:

numbers = [1, 2, 3]

result = list(map(lambda x: x * 2, numbers))

Filter

filter() returns only those elements that satisfy a condition.

Example:

numbers = [1, 2, 3, 4, 5]

result = tuple(filter(lambda x: x % 2 == 0, numbers))

Reduce

reduce() applies a function repeatedly to reduce all elements into a single value.

Example:

from functools import reduce

result = reduce(lambda x, y: x + y, [1, 2, 3, 4])

Q41. What are Decorators? And how to use them.

Answer:

A Decorator is a function that adds extra functionality to another function


without modifying its original code. It is applied using the @ symbol.

Example:
def deco(func):

def wrapper():

print("Hi")

func()

return wrapper

@deco

def greet():

print("Hello")

greet()

Output

Hi

Hello

Q42. Generators & yield vs return.

Answer:

A generator is a special type of function that produces values one at a time using
the yield keyword instead of returning all values at once. Generators are memory
efficient and are useful for working with large datasets.

def numbers():
yield 1
yield 2
yield 3

for x in numbers():
print(x)

Difference between yield and return

yield return

Returns one value at a time Returns all at once

Pauses the function Ends the function


yield return

Used in generators Used in normal functions

Memory efficient Less memory efficient for large data

42 Q. What is yield in Python?

Answer:

The yield keyword is used to create a generator. It returns one value at a time and
pauses the function, so it can continue from the same point the next time it is
called.

Q43. Difference between Deep Copy and Shallow Copy.

Shallow Copy creates a new object but shares the nested objects with the original
object.

Deep Copy creates a completely independent copy of the object, including all
nested objects.

Shallow Copy Deep Copy

Copies the outer object and all nested


Copies only the outer object.
objects.

Nested objects are shared with the Nested objects are copied
original object. independently.

Changes in nested objects affect both Changes do not affect the original
copies. object.

Faster and uses less memory. Slower and uses more memory.

Created using [Link](). Created using [Link]().

Example:

import copy

list1 = [[1, 2], [3, 4]]

Shallow Copy:
list2 = [Link](list1)

Deep Copy:

list3 = [Link](list1)

Q44. What is Duck Typing?

Answer:

Duck Typing is a concept in Python where the type of an object is determined by its
behavior, not by its class. If an object has the required methods or attributes, it can
be used.

Example:

class Duck:

def sound(self):

print("Quack")

class Dog:

def sound(self):

print("Bark")

def make_sound(animal):

[Link]()

Q45. Explain Python Memory Allocation & Garbage Collection.

Answer:

1. Memory Allocation: Python automatically allocates memory for variables and


objects when they are created.
2. Garbage Collection: Python automatically frees memory by removing objects
that are no longer in use, helping to prevent memory leaks.

Example :
a = [1, 2, 3]
del a # Object becomes eligible for garbage collection

Q46. What are Iterators and Iterables?


Answer:

An iterable is any object that can be looped over using a for loop, such as a list,
tuple, string, dictionary, or file.

An iterator is an object that returns one item at a time using the next() function.

Difference:

Iterable Iterator

Can be used in a for loop. Produces one value at a time.

Examples: List, Tuple, String, Dictionary. Created using iter().

Does not keep track of the current position. Keeps track of the current position.

Q47. Explain Comprehensions (List, Dict, Set) in depth.

Answer:

Comprehensions provide a short and readable way to create collections (lists,


dictionaries, and sets) using a single line of code.

1. List Comprehension

Creates a new list.

Example:

squares = [x * x for x in range(5)]

2. Dictionary Comprehension

Creates a new dictionary.

Example:

squares = {x: x * x for x in range(5)}

3. Set Comprehension

Creates a set of unique values.

Example:

unique = {x * x for x in [1, 2, 2, 3]}

Advantages:

• Faster than traditional loops.


• Cleaner and more readable code.

• Easy to create collections in a single line.

Q48. Explain Type Hinting in Python.

Answer:

Type Hinting allows programmers to specify the expected data type of variables,
function parameters, and return values. It improves code readability and helps IDEs
detect errors.

Example:

def add(a: int, b: int) -> int:

return a + b

Q49. What is Global Interpreter Lock (GIL)?

Answer:

The Global Interpreter Lock (GIL) is a mechanism in CPython that allows only one
thread to execute Python bytecode at a time. It protects shared memory and
prevents multiple threads from executing Python code simultaneously.

Q50. What is Multithreading in Python?

Answer:

Multithreading is a technique that allows multiple threads to run concurrently


within a single process. It is useful for I/O-bound tasks such as file handling,
networking, and downloading data.

Example:

import threading

def task():

print("Thread Running")

t = [Link](target=task)

[Link]()
Q52. Explain File Handling and Context Managers (with Keyword).

Answer:

File handling is used to create, read, write, and update files in Python.

The with statement is a context manager that automatically closes the file after
use, even if an exception occurs.

Read a File

with open("[Link]", "r") as file:

print([Link]())

Write a File

with open("[Link]", "w") as file:

[Link]("Hello Python")

Q53. Explain Exception Hierarchy and Custom Exceptions.

Answer:

Python exceptions are organized in a hierarchy. All exceptions are derived from the
BaseException class, and most common exceptions inherit from the Exception
class.

Common Exceptions:

• ZeroDivisionError

• ValueError

• TypeError

• IndexError

• KeyError

• FileNotFoundError

A custom exception is a user-defined exception created by inheriting from the


Exception class.

Example:

class MyError(Exception):

pass
Q54. Difference between Class and Object.

Answer:

Class Object

A blueprint or template. An instance of a class.

Uses the properties and methods of


Defines properties and methods.
the class.

Created using the class keyword. Created by calling the class.

Does not occupy memory until objects


Occupies memory when created.
are created.

Q55. Explain __init__(), __new__(), and other Dunder Methods.

Answer:

__new__()

• Creates a new object.

• Called before __init__().

__init__()

• Initializes the object after it is created.

• Used to assign values to object attributes.

Common Dunder Methods:

• __str__() – Returns a readable string representation of an object.

• __repr__() – Returns the official string representation.

• __len__() – Returns the length of an object.

• __del__() – Called when an object is destroyed.

Q56. Class Methods vs Static Methods vs Instance Methods.

Answer:
Instance Method Class Method Static Method

Works with object Works with class Independent of class and object
data. data. data.

Uses self. Uses cls. Uses no special parameter.

Called using an Uses


Uses @staticmethod.
object. @classmethod.

Q57. Method Overloading vs Method Overriding in Python.

Answer:

Method Overloading Method Overriding

Same method name with different Same method name in parent and
parameters. child classes.

Python does not support true


Fully supported using inheritance.
overloading directly.

Achieved using default or variable Achieved by redefining the parent


arguments. method.

Q58. Explain Properties and Descriptors.

Answer:

A property is a special attribute that allows controlled access to an object's data


using the @property decorator.

A descriptor is an object that controls how attributes are accessed, modified, or


deleted using methods like __get__(), __set__(), and __delete__().

Descriptors are the mechanism behind properties in Python.

Q59. What are Modules and Packages? How to create and install?

Answer:

A module is a single Python file that contains reusable code such as: - Functions -

Classes - Variables
Python uses modules to organize code and avoid writing the same logic again and

again.

Example:

import math

print([Link](16))

Here, math is a module that provides mathematical functions.

A package is a collection of multiple related modules.

Create a Module

Create a file named [Link].

# [Link]

def greet():

print("Hello")

Import a Module

import mymodule

[Link]()

Create a Package

1. Create a folder.
2. Add Python module files (.py) to the folder.
3. Add an __init__.py file.

Install a Package

pip install numpy

Q60. Explain Function Closures & Closures with State.

Answer:

A closure is a function that remembers and can access the variables of its outer
function, even after the outer function has finished execution.
A closure with state remembers the value of the outer variables between function
calls, allowing it to preserve state without using global variables.

Example:

def outer(x):
def inner():
return x
return inner

func = outer(10)

print(func())

Output:

10

Q61. Explain how Python Dictionaries are implemented.

Answer:

Python dictionaries are implemented using a hash table. Each key is converted
into a hash value using a hash function, which allows Python to quickly store and
retrieve values.

Key Points:

1. Dictionaries store data as key-value pairs.

2. Keys must be unique and immutable (e.g., int, str, tuple).

3. Values can be of any data type.

4. Dictionary operations like search, insert, and delete are very fast, with an
average time complexity of O(1).

5. Python uses hashing to efficiently locate values based on their keys.

Q63. Internals of Python List Resizing.

Answer:

Python lists are dynamic arrays. When a list becomes full, Python automatically
allocates a larger memory block and copies the existing elements into it. This
resizing improves performance by reducing the number of memory reallocations.
Q64. Explain Python Bytecode and dis module.

Answer:

Python source code is first compiled into bytecode (.pyc), which is executed by the
Python Virtual Machine (PVM). The dis module is used to display the bytecode
instructions of Python programs, helping developers understand how Python
executes code.

Q65. Concurrency – Sync vs Threads vs Processes.

Answer:

Synchronous Threads Processes

Tasks execute one Multiple threads run Multiple processes run


after another. within one process. independently.

Best for I/O-bound


Simple but slower. Best for CPU-bound tasks.
tasks.

Can run in parallel on


No parallel execution. Limited by GIL.
multiple CPU cores.

Q66. Explain Data Model and Special Methods deeply.

Answer:

Python's data model defines how objects behave. Special methods (dunder
methods) begin and end with double underscores (__). They allow objects to
support built-in operations.

Common Special Methods:

• __init__() – Initializes an object.

• __new__() – Creates an object.

• __str__() – Returns a readable string.

• __repr__() – Returns the official string representation.

• __len__() – Returns the object's length.

• __eq__() – Compares two objects.


• __add__() – Defines the behavior of the + operator.

Q67. Explain Memory Leaks in Python and how to debug.

Answer:

A memory leak occurs when memory is not released even though it is no longer
needed. Although Python has Garbage Collection, memory leaks can occur due to
circular references or objects that remain referenced.

Debugging Tools:

• gc module

• tracemalloc

• memory_profiler

• objgraph

Q68. Explain Introspection in Python.

Answer:

Introspection is the ability of Python to examine information about objects at


runtime. It helps developers inspect an object's type, attributes, methods, and
documentation.

Common Introspection Functions:

• type()

• id()

• dir()

• help()

• isinstance()

• issubclass()

Q69. Explain how Class Attributes and Instance Attributes are resolved.

Answer:
Class attributes are shared by all objects of a class, while instance attributes
belong to individual objects.

Python first searches for an attribute in the instance. If it is not found, Python
searches in the class, then in the parent classes according to the Method
Resolution Order (MRO).

Q70. Explain Serialization & Pickling Limitations.

Answer:

Serialization is the process of converting an object into a format that can be stored
or transmitted. Pickling is Python's built-in serialization process using the pickle
module.

Limitations:

1. Pickled data is not secure from untrusted sources.

2. Not compatible with all programming languages.

3. Some objects (such as open files and threads) cannot be pickled.

4. Different Python versions may have compatibility issues.

Q71. Explain different Python implementations (CPython, PyPy, Jython, etc.).

Answer:

Python has several implementations, each designed for different platforms and use
cases.

1. CPython

• The official and most widely used Python implementation.

• Written in C.

• Compiles Python code into bytecode and executes it using the Python Virtual
Machine (PVM).

2. PyPy

• Written in Python (RPython).

• Uses Just-In-Time (JIT) compilation.

• Faster than CPython for many programs.


3. Jython

• Written in Java.

• Runs on the Java Virtual Machine (JVM).

• Can directly use Java libraries.

4. IronPython

• Written in C#.

• Runs on the .NET Framework / .NET.

• Can directly use .NET libraries.

• Q106. What is zip()?


• zip() is a built-in function that combines two or more iterables into a single iterable
of tuples. It pairs elements based on their positions and stops when the shortest
iterable ends.

What is assert?

• Answer:
• assert is a debugging statement used to test whether a condition is True. If the
condition is False, Python raises an AssertionError. It helps detect programming
errors during development.

Q73. What is the difference between append() and extend()?

Answer:

append() extend()

Adds a single element. Adds all elements of an iterable.

Increases the list by one element. Adds multiple elements.

Q74. Difference between remove(), pop(), and del.

Answer:
remove() pop() del

Removes by Removes by index and returns Deletes an object or


value. the value. element.

Q75. Difference between sort() and sorted().

Answer:

sort() sorted()

Sorts the original list. Returns a new sorted list.

Works only with lists. Works with any iterable.

Q76. What is the difference between deepcopy() and assignment (=)?

Answer:

= creates another reference to the same object, while deepcopy() creates a


completely independent copy.

Q77. What is self in Python?

Answer:

self refers to the current object of a class. It is used to access instance variables and
methods.

Q79. What is Method Resolution Order (MRO)?

Answer:

MRO defines the order in which Python searches for methods and attributes in
inheritance. It is especially important in multiple inheritance.

Q82. What is Exception Handling?

Answer:

Exception Handling is a mechanism to handle runtime errors using try, except, else,
and finally, allowing the program to continue instead of terminating unexpectedly.
Q83. What is finally?

Answer:

The finally block always executes, whether an exception occurs or not. It is


commonly used to close files, release resources, or perform cleanup.

Q84. What is enumerate()?

Answer:

enumerate() returns both the index and the value while iterating over an iterable.

Q85. What is zip()?

Answer:

zip() combines two or more iterables into a single iterable of tuples.

Q86. What is enumerate() vs range()?

Answer:

enumerate() range()

Returns index and value. Returns only numbers.

Used while iterating over data. Used to generate a sequence of numbers.

Q87. What is the difference between * and ** in function calls?

Answer:

• * unpacks iterable objects like lists and tuples.

• ** unpacks dictionaries into keyword arguments.

Q89. What is Recursion?

Answer:
Recursion is a technique in which a function calls itself until a base condition is
reached.

Q91. What is __name__ in Python?

Answer:

__name__ is a special built-in variable. It is set to "__main__" when a Python file is


executed directly and to the module name when it is imported.

Q93. What is the difference between id() and type()?

Answer:

id() type()

Returns the memory address (identity) of an Returns the data type of an


object. object.

Q96. What is Method Chaining?

Answer:

Method chaining means calling multiple methods one after another in a single
statement because each method returns an object.

You might also like