Python
Sunday, February 16, 2025 10:37 PM
Sure! Below is a structured version of your Python notes, including all the questions you
provided, along with the best possible descriptions.
Python Interview Notes
1. What is Python?
Python is a high-level, interpreted programming language known for its simplicity and
readability. It supports multiple programming paradigms, including procedural, object-
oriented, and functional programming.
2. What are the key features of Python?
• Easy to Learn and Use – Python has a simple syntax similar to English.
• Interpreted Language – Python does not need compilation; it is executed line by line.
• Dynamically Typed – No need to declare variable types.
• Object-Oriented – Supports OOP principles like inheritance and polymorphism.
• Large Standard Library – Includes modules for networking, web development, data
science, etc.
• Platform-Independent – Can run on Windows, macOS, Linux, etc.
3. What are Python's data types?
• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Text Type: str
• Set Types: set, frozenset
• Mapping Type: dict
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview
4. What is the difference between a list and a tuple?
Feature List Tuple
Mutable Yes No
Syntax [] ()
Performance Slower (due to mutability) Faster
Usage Used when data needs modification Used for fixed data
5. What is the difference between is and == in Python?
• is checks whether two variables refer to the same object in memory.
• == checks whether two variables have the same value.
Example:
a = [1, 2, 3]
b=a
print(a is b) # True (same memory location)
print(a == b) # True (same values)
6. What is a dictionary in Python?
A dictionary (dict) is a key-value pair data structure. It is unordered, mutable, and does not
allow duplicate keys.
Example:
student = {'name': 'John', 'age': 22}
print(student['name']) # Output: John
Python Page 1
print(student['name']) # Output: John
7. What are Python functions?
Functions in Python are blocks of reusable code that perform a specific task.
Example:
def greet(name):
return "Hello " + name
print(greet("Alice"))
8. Explain args and kwargs in Python.
• *args: Allows a function to accept multiple positional arguments.
• **kwargs: Allows a function to accept multiple keyword arguments.
Example:
def my_func(*args, **kwargs):
print(args) # Tuple of values
print(kwargs) # Dictionary of key-value pairs
my_func(1, 2, 3, name="Alice", age=25)
9. What is the difference between deep copy and shallow copy?
• Shallow Copy ([Link]()): Copies references, changes in the original affect the copy.
• Deep Copy ([Link]()): Creates an independent copy of nested objects.
Example:
import copy
a = [[1, 2], [3, 4]]
b = [Link](a) # Deep copy prevents modification in the original
10. What is list comprehension?
List comprehension provides a concise way to create lists.
Example:
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
11. What is the difference between a generator and an iterator?
• Iterator: Implements __iter__() and __next__(), used in loops.
• Generator: Uses yield to produce values lazily, saving memory.
Example of a generator:
def my_gen():
yield 1
yield 2
yield 3
gen = my_gen()
print(next(gen)) # 1
print(next(gen)) # 2
12. What is Python’s Global Interpreter Lock (GIL)?
GIL ensures that only one thread executes Python bytecode at a time, limiting true
parallelism in multi-threading.
13. What is the difference between @staticmethod, @classmethod,
and instance methods?
• Instance Method: Uses self to access instance attributes.
• Class Method (@classmethod): Uses cls, affects the class.
• Static Method (@staticmethod): No access to self or cls, behaves like a regular
function inside a class.
Example:
class MyClass:
def instance_method(self):
Python Page 2
def instance_method(self):
return "Instance method"
@classmethod
def class_method(cls):
return "Class method"
@staticmethod
def static_method():
return "Static method"
14. What are Python’s memory management features?
• Automatic garbage collection (gc module)
• Reference counting
• Memory pools (PyMalloc)
• Dynamic memory allocation
15. What is duck typing in Python?
If an object behaves like a certain type (has required methods/attributes), it can be used as
that type, regardless of its actual class.
Example:
class Duck:
def quack(self):
return "Quack!"
def make_quack(animal):
return [Link]()
duck = Duck()
print(make_quack(duck)) # Quack!
16. How do you handle exceptions in Python?
Using try-except-finally.
Example:
try:
x=1/0
except ZeroDivisionError as e:
print("Cannot divide by zero")
finally:
print("Execution completed")
17. What is the difference between deepcopy() and copy()?
• copy(): Creates a shallow copy.
• deepcopy(): Creates an independent deep copy.
18. What are lambda functions in Python?
Lambda functions are anonymous, single-expression functions.
Example:
add = lambda x, y: x + y
print(add(3, 4)) # 7
19. What is a metaclass in Python?
A metaclass is a class for classes. It defines how classes behave.
Example:
class Meta(type):
def __new__(cls, name, bases, attrs):
attrs['custom_attr'] = 100
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
print(MyClass.custom_attr) # 100
Python Page 3
print(MyClass.custom_attr) # 100
20. What is the difference between staticmethod and classmethod?
• staticmethod: Works like a normal function inside a class.
• classmethod: Works at the class level and affects all instances.
21. What is NumPy in Python? Why is it used?
NumPy (Numerical Python) is a powerful library for numerical computing in Python. It
provides support for large, multi-dimensional arrays and matrices, along with mathematical
functions for operations on these arrays.
Key Features of NumPy:
• Efficient array operations
• Element-wise computation
• Broadcasting for operations on arrays of different shapes
• Linear algebra and Fourier transform functions
• Integration with other libraries like Pandas and SciPy
Example: Creating a NumPy array
import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr) # Output: [1 2 3 4]
22. What is Pandas? Why is it used?
Pandas is a Python library used for data analysis and manipulation. It provides flexible data
structures like Series and DataFrame, making it easier to work with structured data.
Key Features of Pandas:
• Series: One-dimensional labeled array
• DataFrame: Two-dimensional labeled data structure
• Handling missing data
• Data manipulation and aggregation
• Integration with NumPy and Matplotlib
Example: Creating a Pandas DataFrame
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = [Link](data)
print(df)
Output:
Name Age
0 Alice 25
1 Bob 30
23. Difference between NumPy and Pandas
Feature NumPy Pandas
Data Structure Multi-dimensional array Tabular data (DataFrame, Series)
(ndarray)
Usage Scientific computing, numerical Data manipulation, analysis
operations
Memory More memory-efficient Uses more memory
Efficiency
Performance Faster for numerical operations Slightly slower for operations involving
large data tables
Ease of Use Less user-friendly for tabular More user-friendly for handling
Python Page 4
Ease of Use Less user-friendly for tabular More user-friendly for handling
data structured data
24. What is a Lambda function in Python?
A Lambda function is an anonymous function defined using the lambda keyword. It is a
single-expression function used where short functions are required.
Syntax:
lambda arguments: expression
Example: Lambda function for addition
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Example: Lambda function inside map()
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]
Example: Lambda function inside filter()
nums = [1, 2, 3, 4, 5, 6]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums) # Output: [2, 4, 6]
Lambda functions are useful in:
• Short, one-time-use functions
• Functional programming (map, filter, reduce)
• Reducing code verbosity
Python Page 5