Python Q & A

What is Python?
Python is a simple and beginner-friendly programming language. It
was created by Guido Van Rossum in 1991 and is widely used for web
development, data science, automation, and more.

Why is Python called an interpreted language?
Python executes code line by line using an interpreter, meaning it
doesn’t require the entire program to be compiled into machine code
before running. This makes testing and debugging faster.

What is PEP 8?
PEP 8 is a style guide for writing Python code. It ensures code is clean,
consistent, and easy to read. Following PEP 8 helps in better
collaboration and understanding among developers.

What are mutable and immutable data types?
● Mutable: These can be changed after creation. Example: Lists
and Dictionaries (you can add, remove, or update their
elements).
● Immutable: These cannot be changed after creation. Example:
Strings and Tuples (once created, their values cannot be
altered).

What is list comprehension?
List comprehension is a compact way to create new lists. It allows you
to write a loop in a single line, making code shorter and more
readable.
Example:
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]

What is the difference between a Set and a Dictionary?
● Set: Unordered collection of unique elements.
Example: {1, 2, 3}.
● Dictionary: Stores data in key-value pairs.
Example: {‘a’: 1, ‘b’: 2}.

What is a lambda function?
A lambda function is a small, anonymous function that you can de
ne

in one line. It is used for simple tasks.
Example:
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

What does pass mean in Python?
The pass statement is used as a placeholder when no action is
required. It prevents errors in situations where a block of code is
required but is not ready yet.
Example:
if True:
pass # No action is taken

What are global and local variables?
● Global Variables: Declared outside any function and
accessible throughout the program.
● Local Variables: Declared inside a function and only
accessible within that function.

What is negative indexing?
Negative indexing allows you to access elements of a list or string
starting from the end.
Example:

lst = [10, 20, 30]
print(lst[-1]) # Output: 30 (last element)

What is slicing in Python?
Slicing is a way to extract parts of a sequence (like lists or strings)
using indices.
Example:
text = “Python”
print(text[1:4]) # Output: yth

What is PIP?
PIP stands for “Python Installer Package.” It is a tool used to install
Python libraries and packages.
Example : pip install numpy

What are *args and kwargs?
*args: Used to pass a variable number of positional arguments to a
function.
Example:
def add(*args):
return sum(args)
print(add(1, 2, 3)) # Output: 6

**kwargs: Used to pass variable keyword arguments (key-value
pairs).
Example:
def greet(**kwargs):
for key, value in kwargs.items():
print(f”{key}: {value}”)
greet(name=”Alice”, age=25) # Output: name: Alice, age: 25

What is a class?
A class is like a blueprint that denes how objects should behave. It

contains attributes (data) and methods (functions).
Example:
class Car:
def __init__(self, brand):
self.brand = brand

What is an object?
An object is an instance of a class. It is created based on the class and
represents speci

c data and behavior.

Example:
car1 = Car(“Toyota”) # car1 is an object of the Car class

What is encapsulation?
Encapsulation is the process of wrapping data (attributes) and
methods into a single unit (class) and restricting access to sensitive
data using access modi

ers like private or protected.

What is inheritance?
Inheritance allows a class (child class) to use properties and methods
of another class (parent class). It helps in reusing code.
Example:
class Vehicle:
def start(self):
print(“Starting…”)

class Car(Vehicle):
Pass
car = Car()
car.start() # Output: Starting…

What is polymorphism?
Polymorphism means the same function behaves differently based on
the context.
Example:
class Animal:
def sound(self):
Pass
class Dog(Animal):
def sound(self):
print(“Bark”)
class Cat(Animal):
def sound(self):
print(“Meow”)
dog = Dog()
dog.sound() # Output: Bark

What is abstraction?
Abstraction hides unnecessary details and shows only the essential
features of an object. It is implemented using abstract classes or
interfaces.
What are namespaces?
Namespaces are containers that hold a mapping between names and
objects. They help avoid name con
icts.

Example:
x = 10 # Global namespace
def my_func():
x = 5 # Local namespace

What is the difference between is and ==?
● is: Checks if two variables refer to the same object in
memory.
● ==: Checks if two variables have the same value.
Example:
a = [1, 2]
b = [1, 2]
print(a == b) # True (values are the same)
print(a is b) # False (different memory locations)

What is a docstring?
A docstring is a special string written as the

rst statement in a

function, class, or module to describe what it does.
Example:
def greet():
“””This function prints a greeting message.”””
print(“Hello!”)

What are the types of operators in Python?
● Arithmetic Operators: +, -, *, /.
● Comparison Operators: ==, !=, .
● Logical Operators: and, or, not.
● Assignment Operators: =, +=, -=.
● Bitwise Operators: &, |, ~.
● Identity Operators: is, is not.
● Membership Operators: in, not in.

What is method overriding?
Method overriding occurs when a child class rede

nes a method from

its parent class with its own implementation.
Example:
class Parent:
def greet(self):
print(“Hello from Parent”)
class Child(Parent):
def greet(self):
print(“Hello from Child”)
child = Child()
child.greet() # Output: Hello from Child

What is the difference between append() and extend()?
append(): Adds one element (e.g., number, string, or list) to the end of
a list.
Example:
lst = [1, 2]
lst.append(3) # Result: [1, 2, 3]
lst.append([4, 5]) # Result: [1, 2, 3, [4, 5]]
extend(): Adds elements of an iterable (like another list) to the list.
Example:
lst = [1, 2]
lst.extend([3, 4]) # Result: [1, 2, 3, 4]

What are Python libraries? Name a few.
Libraries are pre-written code collections that simplify tasks.
Examples:
● NumPy: For numerical computations.
● Pandas: For data manipulation.
● Matplotlib: For data visualization.
● TensorFlow: For machine learning.
What is the difference between a module and a package?
● Module: A single Python

le containing related functions or

classes (e.g., math.py).
● Package: A folder containing multiple modules, along with
an __init__.py

le to treat it as a package.

What is __init__ in Python?
__init__ is a constructor method called when creating an object. It
initializes the object’s attributes.
Example:
class Person:
def __init__(self, name):
self.name = name

p = Person(“John”) # p.name is now “John”

What is a Python decorator?
A decorator is a function that modi

es another function or method’s

behavior without changing its code.
Example:
def decorator(func):
def wrapper():
print(“Before function call”)

func()
print(“After function call”)
return wrapper
@decorator
def say_hello():
print(“Hello!”)
say_hello()

# Output: Before function call -> Hello! -> After function
call

How is exception handling done in Python?
Python uses try, except, else, and finally to handle errors
gracefully.

Example:
try:
x = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero!”)
else:
print(“No errors occurred.”)
finally:
print(“Execution complete.”)

What are iterators and how are they different from generators?
● Iterator: An object that can be iterated (e.g., list). Created using
iter() and iterated with next().
● Generator: A special iterator created using yield, generating
values one at a time to save memory.

What is the use of the with statement in Python?
It ensures proper management of resources like

les by automatically

closing them.
Example:
with open(‘file.txt’, ‘r’) as file:
data = file.read()
# File is automatically closed here.

How is memory managed in Python?
● Private Heap: Stores all Python objects and data.
● Garbage Collection: Automatically removes unused objects.
What is the purpose of Python’s id() function?
id() returns the memory address of an object.
Example:
x = 10
print(id(x)) # Memory address of x
What are list methods like pop() and remove()?
pop(): Removes an item by index and returns it.
Example:
lst = [1, 2, 3]
lst.pop(1) # Removes and returns 2 -> [1, 3]

remove(): Removes the

rst occurrence of a value.

Example:
lst = [1, 2, 3]
lst.remove(2) # Removes 2 -> [1, 3]

What is the difference between shallow copy and deep copy?
Shallow Copy: Copies the top-level object but not nested objects.
Changes in nested objects affect both copies.
Example:
import copy
lst = [[1, 2], [3, 4]]
shallow = copy.copy(lst)
shallow[0][0] = 100
print(lst) # [[100, 2], [3, 4]]

Deep Copy: Copies the object and all nested objects. Changes do not
affect the original.
Example:
deep = copy.deepcopy(lst)
deep[0][0] = 100
print(lst) # Original remains unchanged.