Interview Preparation
Practice real interview questions with detailed answers
232 Questions
Easy
76 questions
PYTHON
#1.1
Q1:
What is Python?
Ans:
Python is a high-level, interpreted, general-purpose programming language known for its readable syntax, dynamic typing, and large standard library, supporting multiple programming paradigms.
PYTHON
#1.2
Q2:
Is Python interpreted or compiled?
Ans:
Python is generally interpreted; source code is compiled to bytecode (.pyc files) which is then executed by the Python Virtual Machine (PVM), so it involves both a compilation step and interpretation.
PYTHON
#1.3
Q3:
What are the key features of Python?
Ans:
Python offers dynamic typing, automatic memory management, a large standard library, readable indentation-based syntax, support for multiple paradigms (procedural, object-oriented, functional), and cross-platform portability.
PYTHON
#1.4
Q4:
What is PEP 8?
Ans:
PEP 8 is Python's official style guide, providing conventions for code layout, naming, and formatting to improve readability and consistency across Python codebases.
PYTHON
#1.5
Q5:
How do you write comments in Python?
Ans:
Single-line comments start with #, and multi-line comments/docstrings are typically written using triple quotes (''' or """).
Code Example
# This is a comment
"""
This is a docstring or multi-line comment
"""
PYTHON
#1.6
Q6:
How do you declare a variable in Python?
Ans:
Python variables don't require explicit type declaration; you simply assign a value to a name, and the interpreter infers the type dynamically.
Code Example
x = 10
name = 'Alice'
PYTHON
#1.7
Q7:
What are the rules for naming variables in Python?
Ans:
Variable names must start with a letter or underscore, can contain letters, digits, and underscores, cannot be a reserved keyword, and are case-sensitive.
PYTHON
#1.8
Q8:
What is dynamic typing in Python?
Ans:
Dynamic typing means a variable's type is determined at runtime based on the value assigned to it, and the same variable name can be reassigned to hold values of different types.
Code Example
x = 5
x = 'hello' # allowed, x is now a string
PYTHON
#1.9
Q9:
What are Python's built-in data types?
Ans:
Python's core built-in types include int, float, complex, str, bool, list, tuple, dict, set, frozenset, and NoneType.
PYTHON
#1.10
Q10:
What is the difference between a list and a tuple?
Ans:
A list is mutable (elements can be changed, added, or removed) and defined with square brackets, while a tuple is immutable and defined with parentheses, making tuples generally faster and hashable when containing only immutable elements.
Code Example
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
PYTHON
#1.11
Q11:
How do you check the type of a variable in Python?
Ans:
The type() function returns an object's type, and isinstance() checks whether an object is an instance of a given type or class.
Code Example
print(type(5)) # <class 'int'>
print(isinstance(5, int)) # True
PYTHON
#1.12
Q12:
What is None in Python?
Ans:
None is a special singleton value representing the absence of a value or a null value, and is the default return value of functions that don't explicitly return anything.
PYTHON
#1.13
Q13:
How do you check if a variable is None?
Ans:
You should use 'is None' rather than '== None', since 'is' checks identity and None is a singleton, making it the recommended and slightly faster comparison.
Code Example
if value is None:
print('No value')
PYTHON
#1.14
Q14:
What is the difference between == and is in Python?
Ans:
== compares the values of two objects for equality, while 'is' compares their identity, checking whether they refer to the exact same object in memory.
Code Example
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
PYTHON
#1.15
Q15:
What are Python keywords?
Ans:
Keywords are reserved words with special meaning in the language (like if, else, def, class, import, return) that cannot be used as variable or function names.
PYTHON
#1.16
Q16:
How do you take user input in Python?
Ans:
The input() function reads a line of text from standard input as a string, which can then be converted to another type if needed.
Code Example
name = input('Enter your name: ')
age = int(input('Enter your age: '))
PYTHON
#1.17
Q17:
What is an f-string in Python?
Ans:
f-strings (formatted string literals), introduced in Python 3.6, allow embedding expressions directly inside string literals using curly braces, prefixed with an 'f'.
Code Example
name = 'Tom'
print(f'Hello, {name}! You are {2024-1999} years old.')
PYTHON
#1.18
Q18:
What are the different types of operators in Python?
Ans:
Python supports arithmetic, comparison, assignment, logical, bitwise, membership (in, not in), and identity (is, is not) operators.
PYTHON
#1.19
Q19:
What is the difference between / and // in Python?
Ans:
/ performs true division and always returns a float, while // performs floor division, returning the largest integer less than or equal to the result.
Code Example
print(7 / 2) # 3.5
print(7 // 2) # 3
PYTHON
#1.20
Q20:
What does the ** operator do?
Ans:
** is the exponentiation operator, raising the left operand to the power of the right operand.
Code Example
print(2 ** 3) # 8
PYTHON
#1.21
Q21:
What is the modulus operator used for in Python?
Ans:
The % operator returns the remainder of dividing the left operand by the right operand.
Code Example
print(10 % 3) # 1
PYTHON
#1.22
Q22:
How do you write an if-elif-else statement in Python?
Ans:
Python uses if, elif (else if), and else keywords, with code blocks defined by indentation rather than braces.
Code Example
if age < 13:
print('Child')
elif age < 20:
print('Teenager')
else:
print('Adult')
PYTHON
#1.23
Q23:
How does Python define code blocks instead of using braces?
Ans:
Python uses consistent indentation (whitespace) to define the scope of code blocks like loops, functions, and conditionals, rather than curly braces used in many other languages.
PYTHON
#1.24
Q24:
What is a for loop used for in Python?
Ans:
A for loop iterates over the items of any iterable (list, tuple, string, range, dict, etc.), executing the loop body once per item.
Code Example
for i in range(5):
print(i)
PYTHON
#1.25
Q25:
What is the range() function used for?
Ans:
range() generates a sequence of numbers, commonly used for looping a specific number of times, accepting start, stop, and step arguments.
Code Example
for i in range(2, 10, 2):
print(i) # 2 4 6 8
PYTHON
#1.26
Q26:
What is the difference between break, continue, and pass?
Ans:
break exits the loop entirely, continue skips to the next iteration, and pass is a no-op placeholder statement that does nothing, often used where syntax requires a statement but no action is needed.
PYTHON
#1.27
Q27:
What is a while loop used for?
Ans:
A while loop repeatedly executes a block of code as long as a specified condition remains true.
Code Example
i = 0
while i < 5:
print(i)
i += 1
PYTHON
#1.28
Q28:
How do you define a function in Python?
Ans:
Functions are defined using the def keyword, followed by the function name, parameters in parentheses, a colon, and an indented body.
Code Example
def greet(name):
return f'Hello, {name}'
PYTHON
#1.29
Q29:
What is a default parameter value in Python?
Ans:
A default value can be assigned to a parameter in the function definition, making that argument optional when the function is called.
Code Example
def greet(name='Guest'):
return f'Hello, {name}'
PYTHON
#1.30
Q30:
What is the difference between positional and keyword arguments?
Ans:
Positional arguments are matched to parameters by their order in the function call, while keyword arguments are matched by explicitly naming the parameter, allowing them to be passed in any order.
Code Example
def greet(name, greeting):
print(f'{greeting}, {name}')
greet(greeting='Hi', name='Tom')
PYTHON
#1.31
Q31:
What are lambda functions in Python?
Ans:
A lambda function is a small, anonymous function defined with the lambda keyword, limited to a single expression, often used for short throwaway functions passed to other functions.
Code Example
square = lambda x: x * x
print(square(5)) # 25
PYTHON
#1.32
Q32:
What does the return statement do in a function without an explicit value?
Ans:
A bare return statement (or falling off the end of a function without any return) causes the function to return None.
PYTHON
#1.33
Q33:
What is a docstring in Python?
Ans:
A docstring is a string literal that appears as the first statement in a module, function, class, or method, used to document its purpose, accessible via the __doc__ attribute or help().
Code Example
def add(a, b):
"""Return the sum of a and b."""
return a + b
PYTHON
#1.34
Q34:
How do you find the length of a string in Python?
Ans:
The built-in len() function returns the number of characters in a string.
Code Example
print(len('Hello')) # 5
PYTHON
#1.35
Q35:
How do you concatenate strings in Python?
Ans:
Strings can be concatenated using the + operator, the join() method, or f-strings/format() for combining with other values.
Code Example
full = 'Hello' + ' ' + 'World'
PYTHON
#1.36
Q36:
What is string slicing in Python?
Ans:
Slicing extracts a substring using the syntax string[start:stop:step], where start is inclusive and stop is exclusive, and negative indices count from the end.
Code Example
s = 'Hello World'
print(s[0:5]) # 'Hello'
print(s[-5:]) # 'World'
PYTHON
#1.37
Q37:
How do you reverse a string in Python?
Ans:
A common idiom is to slice the string with a step of -1, though reversed() combined with ''.join() also works.
Code Example
s = 'hello'
print(s[::-1]) # 'olleh'
PYTHON
#1.38
Q38:
How do you check if a string contains a substring?
Ans:
You can use the 'in' operator to check membership, or the str.find()/str.index() methods to locate the position.
Code Example
if 'World' in 'Hello World':
print('found')
PYTHON
#1.39
Q39:
How do you split a string into a list?
Ans:
The str.split() method divides a string into a list of substrings based on a specified delimiter (whitespace by default).
Code Example
parts = 'a,b,c'.split(',') # ['a', 'b', 'c']
PYTHON
#1.40
Q40:
How do you join a list of strings into one string?
Ans:
The str.join() method concatenates elements of an iterable using the string it's called on as the separator.
Code Example
result = ', '.join(['a', 'b', 'c']) # 'a, b, c'
PYTHON
#1.41
Q41:
How do you convert a string to uppercase or lowercase?
Ans:
str.upper() converts all characters to uppercase, and str.lower() converts all characters to lowercase.
PYTHON
#1.42
Q42:
How do you remove leading/trailing whitespace from a string?
Ans:
str.strip() removes whitespace (or specified characters) from both ends; lstrip() and rstrip() remove only from the left or right respectively.
Code Example
print(' hello '.strip()) # 'hello'
PYTHON
#1.43
Q43:
How do you check if a string starts or ends with a given substring?
Ans:
str.startswith() and str.endswith() check whether a string begins or ends with a specified substring, returning a boolean.
Code Example
print('hello.py'.endswith('.py')) # True
PYTHON
#1.44
Q44:
How do you add an element to a list?
Ans:
list.append() adds a single element to the end, while list.extend() adds all elements from an iterable, and list.insert() adds an element at a specific index.
Code Example
nums = [1, 2]
nums.append(3) # [1, 2, 3]
PYTHON
#1.45
Q45:
How do you remove an element from a list?
Ans:
list.remove(value) removes the first matching value, list.pop(index) removes and returns an element at a given index (or the last one by default), and del list[index] deletes by index.
Code Example
nums = [1, 2, 3]
nums.remove(2) # [1, 3]
nums.pop() # removes last, returns 3
PYTHON
#1.46
Q46:
What is the difference between a list and a set in Python?
Ans:
A list is an ordered, mutable collection that allows duplicate elements, while a set is an unordered, mutable collection of unique, hashable elements optimized for fast membership testing.
PYTHON
#1.47
Q47:
What is a dictionary in Python?
Ans:
A dictionary is an unordered (insertion-ordered since Python 3.7) collection of key-value pairs, providing fast average O(1) lookup, insertion, and deletion by key.
Code Example
person = {'name': 'Alice', 'age': 30}
PYTHON
#1.48
Q48:
How do you safely get a value from a dictionary without raising an error if the key is missing?
Ans:
The dict.get(key, default) method returns the value for a key if present, or a specified default (None if omitted) instead of raising a KeyError.
Code Example
age = person.get('age', 0)
PYTHON
#1.49
Q49:
What is the difference between dict.get() and dict[key]?
Ans:
dict[key] raises a KeyError if the key doesn't exist, while dict.get(key) returns None (or a specified default) instead of raising an exception.
PYTHON
#1.50
Q50:
How do you iterate over key-value pairs of a dictionary?
Ans:
The dict.items() method returns key-value pairs as tuples, commonly used in a for loop to unpack both key and value.
Code Example
for key, value in person.items():
print(key, value)
PYTHON
#1.51
Q51:
What is the difference between append() and extend() on a list?
Ans:
append() adds its single argument as one new element at the end of the list, while extend() iterates over its argument and adds each individual element to the list.
Code Example
a = [1, 2]
a.append([3, 4]) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4]) # [1, 2, 3, 4]
PYTHON
#1.52
Q52:
What is the difference between list.sort() and sorted()?
Ans:
list.sort() sorts the list in place and returns None, while sorted() returns a new sorted list (or iterable-derived list) and leaves the original unchanged, working on any iterable.
PYTHON
#1.53
Q53:
What does the enumerate() function do?
Ans:
enumerate() adds a counter to an iterable, returning pairs of (index, element), commonly used in for loops when both the position and value are needed.
Code Example
for i, val in enumerate(['a', 'b', 'c']):
print(i, val)
PYTHON
#1.54
Q54:
How do you define a class in Python?
Ans:
Classes are defined using the class keyword followed by the class name and a colon, with methods and attributes defined in the indented body.
Code Example
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f'{self.name} says woof'
PYTHON
#1.55
Q55:
What is the __init__ method used for?
Ans:
__init__ is a special method (constructor) automatically called when a new instance of a class is created, typically used to initialize instance attributes.
PYTHON
#1.56
Q56:
What is 'self' in Python class methods?
Ans:
'self' refers to the current instance of the class and is conventionally the first parameter of instance methods, allowing access to instance attributes and other methods.
PYTHON
#1.57
Q57:
What is inheritance in Python?
Ans:
Inheritance allows a class (subclass) to acquire attributes and methods from another class (superclass), specified by passing the parent class in parentheses after the class name.
Code Example
class Animal:
def eat(self):
print('Eating')
class Dog(Animal):
pass
PYTHON
#1.58
Q58:
What is method overriding in Python?
Ans:
Method overriding occurs when a subclass defines a method with the same name as one in its parent class, replacing the inherited behavior for instances of the subclass.
PYTHON
#1.59
Q59:
How do you handle exceptions in Python?
Ans:
You use a try block to wrap risky code, one or more except blocks to catch specific exception types, an optional else block that runs if no exception occurred, and an optional finally block that always executes.
Code Example
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
finally:
print('Done')
PYTHON
#1.60
Q60:
What is the difference between a module and a package in Python?
Ans:
A module is a single .py file containing Python code, while a package is a directory containing multiple modules along with an __init__.py file (optional since Python 3.3 for namespace packages), organizing related modules together.
PYTHON
#1.61
Q61:
How do you import a module in Python?
Ans:
You use the import statement, optionally with 'as' to alias it, or 'from module import name' to import specific attributes directly.
Code Example
import math
from math import sqrt
import numpy as np
PYTHON
#1.62
Q62:
What is a virtual environment in Python and why is it used?
Ans:
A virtual environment is an isolated Python environment with its own installed packages, separate from the system-wide Python installation, allowing different projects to use different (potentially conflicting) package versions.
Code Example
python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
PYTHON
#1.63
Q63:
What is pip and what is it used for?
Ans:
pip is Python's standard package manager, used to install, upgrade, and remove third-party packages from the Python Package Index (PyPI) or other sources.
Code Example
pip install requests
PYTHON
#1.64
Q64:
What is a requirements.txt file used for?
Ans:
requirements.txt lists a project's dependencies (often with pinned versions), allowing others to install the exact same set of packages using 'pip install -r requirements.txt'.
PYTHON
#1.65
Q65:
What is the Python Standard Library?
Ans:
The Standard Library is the collection of modules that ship with every Python installation, providing built-in functionality for tasks like file I/O, math, networking, data structures, and more, without needing external installation.
PYTHON
#1.66
Q66:
How do you open and read a file in Python?
Ans:
The built-in open() function returns a file object, and methods like read(), readline(), or readlines() retrieve its contents; using a 'with' statement ensures the file is properly closed.
Code Example
with open('data.txt', 'r') as f:
content = f.read()
PYTHON
#1.67
Q67:
What are the common file modes used with open()?
Ans:
Common modes include 'r' (read), 'w' (write, truncating existing content), 'a' (append), 'x' (exclusive creation), and 'b' suffix for binary mode (e.g., 'rb', 'wb').
PYTHON
#1.68
Q68:
Why is it recommended to use the 'with' statement when working with files?
Ans:
The 'with' statement acts as a context manager that automatically closes the file when the block exits, even if an exception occurs, preventing resource leaks from forgotten close() calls.
PYTHON
#1.69
Q69:
How do you write to a file in Python?
Ans:
You open the file in write ('w') or append ('a') mode and call the file object's write() or writelines() method.
Code Example
with open('log.txt', 'a') as f:
f.write('New log entry\n')
PYTHON
#1.70
Q70:
How do you check if a file exists in Python?
Ans:
The os.path.exists() function, or the more modern pathlib.Path.exists() method, checks whether a given path exists on the filesystem.
Code Example
from pathlib import Path
if Path('config.txt').exists():
print('File found')
PYTHON
#1.71
Q71:
How do you work with JSON data in Python?
Ans:
The json module's dumps()/dump() functions convert Python objects to JSON strings/files, while loads()/load() parse JSON strings/files back into Python objects.
Code Example
import json
data = json.loads('{"name": "Tom"}')
json_str = json.dumps(data)
PYTHON
#1.72
Q72:
What are the truthy and falsy values in Python?
Ans:
Falsy values include False, None, 0, 0.0, '', [], (), {}, and set(); virtually all other values, including non-empty containers and non-zero numbers, are truthy.
Code Example
if []: print('truthy')
else: print('falsy') # prints 'falsy'
PYTHON
#1.73
Q73:
What does the built-in sorted() function's key parameter do?
Ans:
The key parameter accepts a function used to extract a comparison value from each element, allowing custom sort criteria without modifying the comparison operators themselves.
Code Example
sorted(words, key=len) # sort strings by length
PYTHON
#1.74
Q74:
What is the difference between sorted() and list.sort() regarding return values?
Ans:
sorted() returns a new sorted list without modifying the original iterable, while list.sort() sorts the list in place and returns None.
PYTHON
#1.75
Q75:
What is the difference between a Python script and a Python module?
Ans:
A script is typically a standalone file meant to be run directly to perform a task, while a module is a file intended to be imported and reused by other scripts or modules, though the same .py file can serve both purposes.
PYTHON
#1.76
Q76:
What is the purpose of the enumerate() function's start parameter?
Ans:
The optional start parameter to enumerate() specifies the initial index value to begin counting from, instead of the default 0.
Code Example
for i, val in enumerate(['a','b','c'], start=1):
print(i, val) # 1 a, 2 b, 3 c
Medium
119 questions
PYTHON
#2.1
Q1:
What is the difference between mutable and immutable objects in Python?
Ans:
Mutable objects (like lists, dicts, sets) can be changed after creation without changing their identity, while immutable objects (like int, str, tuple, frozenset) cannot be modified in place; any 'change' creates a new object.
PYTHON
#2.2
Q2:
What is the difference between type() and isinstance()?
Ans:
type() returns the exact type of an object and doesn't account for inheritance, while isinstance() checks whether an object is an instance of a class or any of its subclasses, making it preferred for type checks involving inheritance.
PYTHON
#2.3
Q3:
What is the difference between Python 2 and Python 3?
Ans:
Python 3 introduced print as a function (not a statement), true division by default with /, unicode strings by default, and removed several Python 2-only constructs; Python 2 reached end-of-life in January 2020 and is no longer maintained.
PYTHON
#2.4
Q4:
What is the purpose of the if __name__ == '__main__': idiom?
Ans:
This checks whether a script is being run directly (in which case __name__ equals '__main__') versus being imported as a module, allowing code to execute only when the file is run directly.
Code Example
if __name__ == '__main__':
main()
PYTHON
#2.5
Q5:
What is the walrus operator in Python?
Ans:
The walrus operator (:=), introduced in Python 3.8, allows assignment of a value to a variable as part of a larger expression, useful for reducing repeated computation in conditions and loops.
Code Example
if (n := len(data)) > 10:
print(f'List is too long: {n} elements')
PYTHON
#2.6
Q6:
What is type hinting in Python?
Ans:
Type hints, introduced in PEP 484, allow optionally annotating variables, function parameters, and return values with expected types, improving readability and enabling static type checking tools like mypy, without enforcing types at runtime.
Code Example
def greet(name: str) -> str:
return f'Hello, {name}'
PYTHON
#2.7
Q7:
Does Python enforce type hints at runtime?
Ans:
No, type hints are not enforced by the Python interpreter at runtime; they serve as documentation and are checked by external static analysis tools like mypy or IDEs.
PYTHON
#2.8
Q8:
What is the difference between 'and'/'or' and '&'/'|' in Python?
Ans:
'and'/'or' are logical operators that short-circuit and work with any truthy/falsy values, while '&'/'|' are bitwise operators performing bit-level operations (and are also overloaded for set operations).
PYTHON
#2.9
Q9:
Does Python support a do-while loop?
Ans:
Python has no built-in do-while construct; the equivalent behavior can be simulated using a while True loop with a break condition at the end.
Code Example
while True:
process()
if not condition:
break
PYTHON
#2.10
Q10:
What are *args and **kwargs used for?
Ans:
*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary, allowing functions to accept a variable number of arguments.
Code Example
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, name='Tom')
PYTHON
#2.11
Q11:
What is the difference between a lambda function and a regular function?
Ans:
A lambda function is restricted to a single expression and has no name (unless assigned to a variable), while a regular function defined with def can contain multiple statements, have a docstring, and supports more complex logic.
PYTHON
#2.12
Q12:
What is variable scope in Python (LEGB rule)?
Ans:
Python resolves variable names using the LEGB rule: Local (current function), Enclosing (any enclosing function), Global (module level), and Built-in (Python's built-in namespace), searched in that order.
PYTHON
#2.13
Q13:
What is the global keyword used for?
Ans:
The global keyword inside a function declares that an assignment to a variable should modify the variable in the global (module-level) scope rather than creating a new local variable.
Code Example
counter = 0
def increment():
global counter
counter += 1
PYTHON
#2.14
Q14:
What is the nonlocal keyword used for?
Ans:
nonlocal, introduced in Python 3, allows a nested function to modify a variable defined in its nearest enclosing (non-global) scope rather than creating a new local variable.
Code Example
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
return count
PYTHON
#2.15
Q15:
What is a closure in Python?
Ans:
A closure is a nested function that captures and remembers the values of variables from its enclosing scope, even after the outer function has finished executing.
Code Example
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
times3 = make_multiplier(3)
print(times3(5)) # 15
PYTHON
#2.16
Q16:
What is a decorator in Python?
Ans:
A decorator is a function that takes another function (or class) as input and extends or modifies its behavior without permanently changing its source code, applied using the @decorator syntax.
Code Example
def logger(func):
def wrapper(*args, **kwargs):
print(f'Calling {func.__name__}')
return func(*args, **kwargs)
return wrapper
@logger
def greet():
print('Hello')
PYTHON
#2.17
Q17:
What is a recursive function in Python?
Ans:
A recursive function calls itself to solve smaller instances of a problem, requiring a base case to terminate the recursion and avoid infinite calls.
Code Example
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
PYTHON
#2.18
Q18:
What are type hints for function parameters and return values?
Ans:
Type hints annotate expected parameter and return types using a colon after parameters and an arrow (->) before the return type, aiding readability and static analysis without runtime enforcement.
Code Example
def add(a: int, b: int) -> int:
return a + b
PYTHON
#2.19
Q19:
What is the difference between str.find() and str.index()?
Ans:
Both search for a substring's position, but find() returns -1 if not found, while index() raises a ValueError if the substring is not present.
PYTHON
#2.20
Q20:
What is the difference between str.replace() and regular expression substitution?
Ans:
str.replace() performs simple literal substring replacement, while re.sub() uses regular expression patterns, allowing more complex and flexible matching and replacement rules.
PYTHON
#2.21
Q21:
How do you format strings using the .format() method?
Ans:
The .format() method substitutes placeholders {} in a string with provided arguments, supporting positional and keyword references.
Code Example
'{} is {} years old'.format('Tom', 25)
PYTHON
#2.22
Q22:
What is the difference between f-strings, .format(), and % formatting?
Ans:
% formatting is the oldest, printf-style approach; .format() is more flexible and readable with named/positional placeholders; f-strings (Python 3.6+) are the most modern, concise, and generally fastest, embedding expressions directly.
PYTHON
#2.23
Q23:
Are strings mutable in Python?
Ans:
No, strings in Python are immutable; any operation that appears to modify a string actually creates and returns a new string object.
PYTHON
#2.24
Q24:
How do you check if a string is numeric?
Ans:
str.isdigit(), str.isnumeric(), or str.isdecimal() check whether a string consists only of digit characters, with subtle differences in which Unicode characters they accept.
PYTHON
#2.25
Q25:
What is a list comprehension in Python?
Ans:
A list comprehension provides a concise syntax to create a new list by applying an expression to each item of an iterable, optionally with a filtering condition.
Code Example
squares = [x**2 for x in range(10) if x % 2 == 0]
PYTHON
#2.26
Q26:
What is a dictionary comprehension?
Ans:
Similar to a list comprehension, it constructs a dictionary by applying key and value expressions to items from an iterable, using curly brace syntax.
Code Example
squares = {x: x**2 for x in range(5)}
PYTHON
#2.27
Q27:
What is a set comprehension?
Ans:
It builds a set using an expression applied to items in an iterable, enclosed in curly braces, automatically removing duplicate results.
Code Example
unique_lengths = {len(word) for word in ['cat', 'dog', 'ox']}
PYTHON
#2.28
Q28:
What is a generator expression?
Ans:
A generator expression uses syntax similar to a list comprehension but with parentheses, producing values lazily one at a time instead of building the entire list in memory at once.
Code Example
gen = (x**2 for x in range(1000000)) # lazy, memory-efficient
PYTHON
#2.29
Q29:
What is the difference between a list comprehension and a generator expression?
Ans:
A list comprehension eagerly builds and stores the entire list in memory, while a generator expression produces items lazily on demand, using significantly less memory for large or infinite sequences.
PYTHON
#2.30
Q30:
What is a frozenset?
Ans:
A frozenset is an immutable version of a set; once created, its elements cannot be added or removed, and it can be used as a dictionary key or set element since it's hashable.
PYTHON
#2.31
Q31:
How do you remove duplicates from a list?
Ans:
Converting the list to a set and back to a list removes duplicates, though this does not preserve order; using dict.fromkeys(list) preserves insertion order in Python 3.7+.
Code Example
unique = list(dict.fromkeys([3, 1, 2, 1, 3])) # [3, 1, 2]
PYTHON
#2.32
Q32:
What is the setdefault() method used for in a dictionary?
Ans:
dict.setdefault(key, default) returns the value for a key if it exists; otherwise, it inserts the key with the given default value and then returns that default.
Code Example
counts = {}
counts.setdefault('a', 0)
counts['a'] += 1
PYTHON
#2.33
Q33:
What is collections.defaultdict used for?
Ans:
defaultdict from the collections module automatically creates a default value for a missing key using a factory function, avoiding manual key-existence checks.
Code Example
from collections import defaultdict
counts = defaultdict(int)
counts['apple'] += 1 # no KeyError
PYTHON
#2.34
Q34:
What is collections.Counter used for?
Ans:
Counter is a dict subclass specialized for counting hashable items, automatically tallying occurrences and providing methods like most_common().
Code Example
from collections import Counter
c = Counter(['a', 'b', 'a', 'c', 'a'])
print(c.most_common(1)) # [('a', 3)]
PYTHON
#2.35
Q35:
What is collections.namedtuple used for?
Ans:
namedtuple creates lightweight, immutable tuple subclasses with named fields, allowing access to elements by name rather than only by index, improving code readability.
Code Example
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
PYTHON
#2.36
Q36:
What is the difference between a shallow copy and a deep copy in Python?
Ans:
A shallow copy (via copy.copy() or slicing) creates a new outer object but shares references to any nested objects, while a deep copy (via copy.deepcopy()) recursively copies nested objects as well, producing a fully independent structure.
Code Example
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
PYTHON
#2.37
Q37:
How do you sort a list of dictionaries by a specific key?
Ans:
You use sorted() or list.sort() with a key function, often a lambda that extracts the desired field from each dictionary.
Code Example
people = [{'name': 'Bob', 'age': 25}, {'name': 'Amy', 'age': 22}]
people.sort(key=lambda p: p['age'])
PYTHON
#2.38
Q38:
What is tuple unpacking in Python?
Ans:
Tuple unpacking assigns each element of a tuple (or any iterable) to separate variables in a single statement, and can use a starred expression to capture remaining elements.
Code Example
a, b, c = (1, 2, 3)
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
PYTHON
#2.39
Q39:
Why are tuples generally faster than lists for fixed collections of data?
Ans:
Tuples are immutable, allowing Python to allocate a fixed amount of memory and perform certain optimizations, and their hashability (when containing only hashable elements) allows use as dictionary keys, unlike lists.
PYTHON
#2.40
Q40:
How do you merge two dictionaries in Python?
Ans:
You can use the {**dict1, **dict2} unpacking syntax, the dict1.update(dict2) method, or the | merge operator introduced in Python 3.9.
Code Example
merged = {**dict1, **dict2}
merged2 = dict1 | dict2 # Python 3.9+
PYTHON
#2.41
Q41:
How do you check if all or any elements of an iterable satisfy a condition?
Ans:
all() returns True if every element is truthy (or satisfies a condition when combined with a generator expression), and any() returns True if at least one element is truthy.
Code Example
print(all(x > 0 for x in [1, 2, 3])) # True
print(any(x < 0 for x in [1, 2, -3])) # True
PYTHON
#2.42
Q42:
What does the zip() function do?
Ans:
zip() combines multiple iterables element-wise into tuples, stopping at the shortest input iterable, and is often used to iterate over parallel sequences together.
Code Example
names = ['Alice', 'Bob']
ages = [30, 25]
for name, age in zip(names, ages):
print(name, age)
PYTHON
#2.43
Q43:
What is the difference between map(), filter(), and a list comprehension?
Ans:
map() applies a function to every item of an iterable, filter() selects items matching a predicate, and both return iterators requiring conversion to a list; a list comprehension often achieves the same result more readably in a single expression.
Code Example
squares = list(map(lambda x: x**2, [1,2,3]))
evens = list(filter(lambda x: x % 2 == 0, [1,2,3,4]))
PYTHON
#2.44
Q44:
What does the functools.reduce() function do?
Ans:
reduce(), found in the functools module, applies a function cumulatively to the items of an iterable, reducing it to a single accumulated value.
Code Example
from functools import reduce
total = reduce(lambda a, b: a + b, [1, 2, 3, 4]) # 10
PYTHON
#2.45
Q45:
What is the difference between an instance attribute and a class attribute?
Ans:
An instance attribute belongs to a specific object and is usually set in __init__ via self, while a class attribute is shared across all instances of the class and is defined directly in the class body.
Code Example
class Dog:
species = 'Canine' # class attribute
def __init__(self, name):
self.name = name # instance attribute
PYTHON
#2.46
Q46:
How do you call a parent class's method from a subclass?
Ans:
The super() function returns a proxy object that allows calling methods of the parent class, commonly used to extend __init__ or override behavior while still invoking the parent's implementation.
Code Example
class Dog(Animal):
def __init__(self, name):
super().__init__()
self.name = name
PYTHON
#2.47
Q47:
Does Python support multiple inheritance?
Ans:
Yes, a Python class can inherit from multiple parent classes by listing them in parentheses, separated by commas, with method resolution order (MRO) determining which parent's method is used in case of conflicts.
Code Example
class Flying:
def move(self): print('Fly')
class Swimming:
def move(self): print('Swim')
class Duck(Flying, Swimming):
pass
PYTHON
#2.48
Q48:
Does Python support method overloading like Java or C++?
Ans:
Python does not support traditional method overloading with multiple same-named methods differing by parameter types; instead, default arguments, *args/**kwargs, or the functools.singledispatch decorator are used to achieve similar flexibility.
PYTHON
#2.49
Q49:
What are dunder (magic) methods in Python?
Ans:
Dunder methods, named with leading and trailing double underscores (like __init__, __str__, __len__), allow classes to define custom behavior for built-in operations such as printing, indexing, or arithmetic.
PYTHON
#2.50
Q50:
What is the difference between __str__ and __repr__?
Ans:
__str__ returns a readable, user-friendly string representation of an object (used by print() and str()), while __repr__ returns an unambiguous, developer-oriented representation (used by repr() and the interactive shell), ideally one that could recreate the object.
Code Example
class Point:
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __str__(self):
return f'({self.x}, {self.y})'
PYTHON
#2.51
Q51:
What is the __eq__ method used for?
Ans:
__eq__ defines custom behavior for the == operator, allowing objects to be compared based on their attribute values rather than default identity comparison.
Code Example
class Point:
def __eq__(self, other):
return self.x == other.x and self.y == other.y
PYTHON
#2.52
Q52:
What is a property in Python and how do you use the @property decorator?
Ans:
@property allows a method to be accessed like an attribute, enabling computed attributes and validation logic while still allowing get/set access with a natural attribute syntax.
Code Example
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14159 * self._radius ** 2
PYTHON
#2.53
Q53:
How do you create a read-only property with a corresponding setter?
Ans:
You define a method decorated with @property for the getter, and another method with the same name decorated with @propertyname.setter to allow controlled assignment.
Code Example
class Circle:
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError('Radius cannot be negative')
self._radius = value
PYTHON
#2.54
Q54:
What is the difference between a class method and a static method?
Ans:
A class method (decorated with @classmethod) receives the class itself as its first argument (cls) and can access/modify class state, while a static method (decorated with @staticmethod) receives neither self nor cls and behaves like a plain function namespaced within the class.
Code Example
class MyClass:
@classmethod
def create(cls):
return cls()
@staticmethod
def helper():
return 'helper'
PYTHON
#2.55
Q55:
What is an abstract base class (ABC) in Python?
Ans:
An abstract base class, defined using the abc module, cannot be instantiated directly and can declare abstract methods (via @abstractmethod) that subclasses must implement, enforcing a contract similar to interfaces.
Code Example
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
PYTHON
#2.56
Q56:
What is duck typing in Python?
Ans:
Duck typing means an object's suitability for use is determined by whether it has the required methods and properties, rather than its explicit type or inheritance ('if it walks like a duck and quacks like a duck...').
PYTHON
#2.57
Q57:
What is encapsulation in Python, given it has no true private keyword?
Ans:
Python uses naming conventions to indicate intended visibility: a single leading underscore (_var) signals 'protected'/internal use, and a double leading underscore (__var) triggers name mangling to make accidental external access harder, though nothing is truly enforced by the language.
PYTHON
#2.58
Q58:
What is operator overloading in Python?
Ans:
Operator overloading allows custom classes to define behavior for built-in operators (+, -, ==, etc.) by implementing the corresponding dunder methods like __add__ or __sub__.
Code Example
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
PYTHON
#2.59
Q59:
What is composition versus inheritance in Python OOP design?
Ans:
Composition builds objects by combining other objects as attributes (a 'has-a' relationship), offering more flexibility and less coupling, while inheritance establishes an 'is-a' relationship that can create rigid, tightly coupled hierarchies if overused.
PYTHON
#2.60
Q60:
What are data classes in Python?
Ans:
Introduced in Python 3.7, the dataclasses module's @dataclass decorator automatically generates __init__, __repr__, and __eq__ methods for classes primarily used to store data, reducing boilerplate code.
Code Example
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
PYTHON
#2.61
Q61:
What is the difference between except Exception and a bare except:?
Ans:
except Exception catches most built-in exceptions but not system-exiting ones like SystemExit or KeyboardInterrupt, while a bare except: catches literally everything including those, which is generally discouraged as it can hide critical signals like Ctrl+C.
PYTHON
#2.62
Q62:
How do you raise a custom exception in Python?
Ans:
You define a class inheriting from Exception (or a more specific built-in exception), and use the raise statement to throw an instance of it.
Code Example
class InsufficientFundsError(Exception):
pass
raise InsufficientFundsError('Not enough balance')
PYTHON
#2.63
Q63:
What is the purpose of the finally block?
Ans:
The finally block contains code that always executes after the try/except blocks, regardless of whether an exception occurred, commonly used for cleanup like closing files or releasing resources.
PYTHON
#2.64
Q64:
What is the difference between an exception and an error in Python?
Ans:
In Python, virtually all runtime errors are represented as exceptions (instances of classes derived from BaseException); there isn't a strict separate 'Error' category as in some other languages, though names like TypeError and ValueError describe specific kinds of exceptions.
PYTHON
#2.65
Q65:
What is the else clause in a try statement used for?
Ans:
The else block executes only if the try block completes without raising an exception, useful for code that should run only on success but shouldn't be wrapped in the try (to avoid catching unrelated exceptions).
Code Example
try:
value = int(user_input)
except ValueError:
print('Invalid input')
else:
print(f'You entered {value}')
PYTHON
#2.66
Q66:
How do you catch multiple exception types in one except block?
Ans:
You specify a tuple of exception types in a single except clause, catching any exception matching one of those types.
Code Example
try:
risky_operation()
except (ValueError, TypeError) as e:
print(f'Error: {e}')
PYTHON
#2.67
Q67:
What is the base class for all built-in exceptions in Python?
Ans:
BaseException is the root class for all exceptions, with Exception being a subclass covering most standard, catchable exceptions (excluding things like SystemExit and KeyboardInterrupt).
PYTHON
#2.68
Q68:
What is a context manager in Python and what does the with statement do?
Ans:
A context manager defines __enter__ and __exit__ methods to manage setup and teardown of a resource; the with statement uses it to ensure the resource is properly cleaned up (like closing a file) even if an exception occurs.
Code Example
with open('file.txt') as f:
data = f.read()
# file automatically closed here
PYTHON
#2.69
Q69:
What is the difference between assert and raising an exception?
Ans:
assert is primarily intended for internal self-checks and debugging, raising an AssertionError if the condition is false, and can be globally disabled with the -O optimization flag; explicit exceptions should be used for expected error conditions in production logic.
Code Example
assert age >= 0, 'Age cannot be negative'
PYTHON
#2.70
Q70:
What is an iterable in Python?
Ans:
An iterable is any object capable of returning its elements one at a time, implementing the __iter__ method (which returns an iterator), such as lists, tuples, strings, and dictionaries.
PYTHON
#2.71
Q71:
What is an iterator in Python?
Ans:
An iterator is an object implementing both __iter__ (returning itself) and __next__ (returning the next value or raising StopIteration when exhausted), produced by calling iter() on an iterable.
Code Example
it = iter([1, 2, 3])
print(next(it)) # 1
print(next(it)) # 2
PYTHON
#2.72
Q72:
What is the difference between an iterable and an iterator?
Ans:
An iterable can produce an iterator (via __iter__) but doesn't track iteration state itself, while an iterator maintains internal state and produces the next value each time __next__ is called, eventually raising StopIteration.
PYTHON
#2.73
Q73:
What is a generator function in Python?
Ans:
A generator function uses the yield keyword instead of return to produce a sequence of values lazily, pausing its state between each yielded value and resuming on the next call to next().
Code Example
def count_up(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up(5):
print(num)
PYTHON
#2.74
Q74:
What is the difference between yield and return in a generator?
Ans:
return exits a function immediately and (in a generator) raises StopIteration, while yield pauses the function, returns a value to the caller, and preserves the function's state to resume execution on the next call.
PYTHON
#2.75
Q75:
What are the benefits of using generators over lists?
Ans:
Generators produce values lazily on demand, using constant memory regardless of sequence size, making them ideal for large or infinite sequences and streaming data processing.
PYTHON
#2.76
Q76:
What is the itertools module used for?
Ans:
itertools provides a collection of fast, memory-efficient tools for creating and working with iterators, including functions like chain(), combinations(), permutations(), cycle(), and groupby().
Code Example
from itertools import chain
combined = list(chain([1,2], [3,4])) # [1,2,3,4]
PYTHON
#2.77
Q77:
What is the purpose of __init__.py?
Ans:
__init__.py marks a directory as a regular Python package, and can contain initialization code or define what's exposed when the package is imported, though it's optional for implicit namespace packages since Python 3.3.
PYTHON
#2.78
Q78:
What is the difference between an absolute import and a relative import?
Ans:
An absolute import specifies the full path from the project's root package (e.g., from mypackage.module import func), while a relative import uses dots to reference modules relative to the current package (e.g., from .module import func).
PYTHON
#2.79
Q79:
What is the sys.path variable used for?
Ans:
sys.path is a list of directory paths that Python searches when importing modules, including the script's directory, installed site-packages, and any paths added via PYTHONPATH.
PYTHON
#2.80
Q80:
What is the pathlib module used for?
Ans:
pathlib provides an object-oriented interface for handling filesystem paths, offering a more readable and cross-platform alternative to the older os.path functions.
Code Example
from pathlib import Path
p = Path('data') / 'file.txt'
print(p.suffix, p.parent)
PYTHON
#2.81
Q81:
How do you read a CSV file in Python?
Ans:
The built-in csv module provides csv.reader() and csv.DictReader() to parse CSV files, or the pandas library's read_csv() function for more advanced data analysis needs.
Code Example
import csv
with open('data.csv') as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
PYTHON
#2.82
Q82:
How do you serialize and deserialize Python objects using pickle?
Ans:
The pickle module's dump()/dumps() functions serialize Python objects into a byte stream, and load()/loads() deserialize them back, though pickle should not be used with untrusted data due to security risks.
Code Example
import pickle
with open('data.pkl', 'wb') as f:
pickle.dump(my_object, f)
PYTHON
#2.83
Q83:
How do you create and start a thread in Python?
Ans:
You can use the threading module's Thread class, passing a target function, and call start() to begin execution and join() to wait for it to finish.
Code Example
import threading
def worker():
print('Working')
t = threading.Thread(target=worker)
t.start()
t.join()
PYTHON
#2.84
Q84:
How do you create a new process in Python using multiprocessing?
Ans:
You use the multiprocessing module's Process class similarly to threading.Thread, but each process runs in its own memory space and Python interpreter instance.
Code Example
from multiprocessing import Process
def worker():
print('Working')
p = Process(target=worker)
p.start()
p.join()
PYTHON
#2.85
Q85:
What is asyncio in Python?
Ans:
asyncio is a standard library module for writing concurrent code using the async/await syntax, based on an event loop that manages cooperative multitasking for I/O-bound operations without using multiple threads.
Code Example
import asyncio
async def main():
await asyncio.sleep(1)
print('Done')
asyncio.run(main())
PYTHON
#2.86
Q86:
What does the await keyword do in Python?
Ans:
await pauses execution of an async function until the awaited coroutine or future completes, yielding control back to the event loop so other tasks can run in the meantime.
PYTHON
#2.87
Q87:
What is the concurrent.futures module used for?
Ans:
concurrent.futures provides a high-level interface (ThreadPoolExecutor and ProcessPoolExecutor) for asynchronously executing callables using pools of threads or processes, simplifying common concurrency patterns.
Code Example
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(process_item, items))
PYTHON
#2.88
Q88:
How do you use regular expressions in Python?
Ans:
The re module provides functions like re.match(), re.search(), re.findall(), and re.sub() to work with regular expression patterns against strings.
Code Example
import re
if re.search(r'\d+', 'Order 123'):
print('Contains a number')
PYTHON
#2.89
Q89:
What is the difference between re.match() and re.search()?
Ans:
re.match() only checks for a match at the beginning of the string, while re.search() scans through the entire string looking for a match anywhere within it.
PYTHON
#2.90
Q90:
What does re.findall() return?
Ans:
re.findall() returns a list of all non-overlapping matches of a pattern in a string, or tuples of groups if the pattern contains multiple capturing groups.
Code Example
re.findall(r'\d+', 'a1 b22 c333') # ['1', '22', '333']
PYTHON
#2.91
Q91:
How do you replace text using a regular expression in Python?
Ans:
re.sub(pattern, replacement, string) replaces all occurrences of a pattern match with a replacement string, supporting backreferences to captured groups.
Code Example
re.sub(r'\d+', '#', 'Order 123 shipped') # 'Order # shipped'
PYTHON
#2.92
Q92:
What are capturing groups in a regex pattern?
Ans:
Capturing groups, defined using parentheses (), allow extracting specific portions of a match, accessible via group() on a Match object or as tuples from findall().
Code Example
m = re.search(r'(\d{3})-(\d{4})', '555-1234')
print(m.group(1), m.group(2)) # '555' '4234' style access
PYTHON
#2.93
Q93:
What is a raw string in Python and why is it used with regex?
Ans:
A raw string, prefixed with r, treats backslashes as literal characters rather than escape sequences, which is useful for regex patterns that heavily use backslashes (like \d or \s) to avoid double-escaping.
Code Example
pattern = r'\d+\s\w+'
PYTHON
#2.94
Q94:
What does the re.compile() function do?
Ans:
re.compile() precompiles a regex pattern into a Pattern object, which can be reused efficiently for multiple match operations without recompiling the pattern each time.
Code Example
pattern = re.compile(r'\d+')
pattern.findall('a1 b2')
PYTHON
#2.95
Q95:
What is unittest in Python?
Ans:
unittest is Python's built-in testing framework, providing a TestCase class with assertion methods (assertEqual, assertTrue, etc.) to structure and run automated tests.
Code Example
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1 + 1, 2)
if __name__ == '__main__':
unittest.main()
PYTHON
#2.96
Q96:
What is pytest and how does it differ from unittest?
Ans:
pytest is a popular third-party testing framework that allows writing simpler test functions (without needing a TestCase class), uses plain assert statements, and offers powerful fixtures and plugins, generally considered more concise than unittest.
Code Example
def test_add():
assert 1 + 1 == 2
PYTHON
#2.97
Q97:
What is a fixture in pytest?
Ans:
A fixture is a function decorated with @pytest.fixture that provides reusable setup (and optional teardown) code for tests, injected as a parameter into test functions that need it.
Code Example
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_sum(sample_data):
assert sum(sample_data) == 6
PYTHON
#2.98
Q98:
What is mocking in unit testing and what module provides it in Python?
Ans:
Mocking replaces real objects or functions with fake substitutes during testing to isolate the code under test from external dependencies; Python's unittest.mock module provides Mock and patch utilities for this purpose.
Code Example
from unittest.mock import patch
with patch('module.some_function', return_value=42):
result = module.some_function()
PYTHON
#2.99
Q99:
How do you debug a Python script interactively?
Ans:
You can insert breakpoint() (or import pdb; pdb.set_trace() in older versions) to pause execution and enter an interactive debugger, allowing you to inspect variables and step through code.
Code Example
def process(data):
breakpoint()
return data * 2
PYTHON
#2.100
Q100:
What is the purpose of logging in Python and how does it differ from using print()?
Ans:
The logging module provides configurable log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), timestamps, and output destinations (file, console, remote), making it far more suitable than print() for production diagnostics and long-term maintainability.
Code Example
import logging
logging.basicConfig(level=logging.INFO)
logging.info('Application started')
PYTHON
#2.101
Q101:
How does Python manage memory?
Ans:
Python uses automatic memory management via reference counting (tracking how many references point to an object) combined with a cyclic garbage collector to detect and clean up reference cycles that reference counting alone can't handle.
PYTHON
#2.102
Q102:
What is reference counting in Python?
Ans:
Reference counting tracks the number of references pointing to an object; when this count drops to zero, the object's memory is immediately deallocated.
PYTHON
#2.103
Q103:
What is the difference between deep copy and shallow copy in terms of memory?
Ans:
A shallow copy creates a new container object but still shares references to the same nested objects as the original, while a deep copy recursively duplicates all nested objects, using more memory but ensuring full independence.
PYTHON
#2.104
Q104:
What is the difference between is and == in terms of performance and correctness?
Ans:
'is' checks object identity (memory address) and is a very fast, simple pointer comparison, while '==' checks value equality and may invoke a custom __eq__ method, potentially being slower but more semantically correct for comparing values.
PYTHON
#2.105
Q105:
How can you profile the performance of Python code?
Ans:
You can use the built-in cProfile module to measure function call counts and execution time, or the timeit module to benchmark small code snippets precisely.
Code Example
import timeit
print(timeit.timeit('sum(range(100))', number=10000))
PYTHON
#2.106
Q106:
What is functools.lru_cache used for?
Ans:
lru_cache is a decorator that caches a function's return values based on its arguments, avoiding redundant computation for repeated calls with the same inputs, useful for optimizing expensive or recursive functions.
Code Example
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
PYTHON
#2.107
Q107:
What does functools.partial do?
Ans:
functools.partial creates a new callable with some arguments of the original function pre-filled, useful for adapting a general function into a more specific one.
Code Example
from functools import partial
square = partial(pow, exp=2)
# or: cube = partial(pow, 2, 3)
PYTHON
#2.108
Q108:
What is the difference between a shallow function (pure function) and one with side effects?
Ans:
A pure function's output depends only on its input arguments and it produces no observable side effects (like modifying global state or printing), making it easier to test and reason about, unlike functions that mutate external state.
PYTHON
#2.109
Q109:
What does the * unpacking operator do when calling a function?
Ans:
Prefixing an iterable with * when calling a function unpacks its elements as separate positional arguments, and ** does the same for a dictionary's items as keyword arguments.
Code Example
def add(a, b, c):
return a + b + c
args = [1, 2, 3]
print(add(*args))
PYTHON
#2.110
Q110:
What is the difference between shallow equality and deep equality for nested data structures?
Ans:
Shallow equality compares only the immediate elements (often by identity for containers), while deep equality (Python's default == for lists/dicts) recursively compares all nested elements' values for equality.
PYTHON
#2.111
Q111:
What is the difference between a shallow module-level variable and a class attribute in terms of scope?
Ans:
A module-level variable is accessible throughout the module (and importable elsewhere), while a class attribute is scoped to the class and its instances, accessed via the class name or an instance.
PYTHON
#2.112
Q112:
What is the Singleton design pattern and how can it be implemented in Python?
Ans:
Singleton ensures a class has only one instance; in Python it can be implemented by overriding __new__ to return a cached instance, using a module (which is naturally a singleton), or using a decorator/metaclass.
PYTHON
#2.113
Q113:
What is the difference between == overloading via __eq__ and default object comparison?
Ans:
By default, objects are compared by identity (memory address) unless __eq__ is overridden to define custom value-based equality logic, such as comparing specific attributes.
PYTHON
#2.114
Q114:
What is the difference between a module-level '__all__' variable's purpose?
Ans:
__all__ is a list of strings defining which names are exported when a module is imported using 'from module import *', controlling the public API surface exposed via wildcard imports.
Code Example
__all__ = ['public_function', 'PublicClass']
PYTHON
#2.115
Q115:
What is the difference between shallow argument unpacking with * in function definitions versus function calls?
Ans:
In a function definition, *args collects extra positional arguments into a tuple; in a function call, *iterable unpacks an iterable's elements as separate positional arguments being passed in.
PYTHON
#2.116
Q116:
What does the built-in id() function return?
Ans:
id() returns a unique integer identifier for an object, representing its memory address in CPython, which remains constant during the object's lifetime.
PYTHON
#2.117
Q117:
What is the difference between shallow copying a dictionary using dict(d) versus d.copy()?
Ans:
Both dict(d) and d.copy() produce a shallow copy of the dictionary with the same top-level key-value pairs but shared references to any nested mutable objects; they are functionally equivalent for this purpose.
PYTHON
#2.118
Q118:
What is the difference between os.system() and subprocess.run() for running shell commands?
Ans:
subprocess.run() is the modern, more flexible and secure way to execute external commands, providing better control over input/output/error streams and avoiding some shell injection risks compared to the older, more limited os.system().
Code Example
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
PYTHON
#2.119
Q119:
What is the difference between shallow slicing and using the copy module for lists?
Ans:
Slicing an entire list (my_list[:]) creates a shallow copy similar to copy.copy(), sharing references to nested objects, while copy.deepcopy() is needed if you require independent nested objects as well.
Hard
37 questions
PYTHON
#3.1
Q1:
What is the else clause on a loop used for in Python?
Ans:
The else block on a for or while loop executes only if the loop completes normally without hitting a break statement.
Code Example
for i in range(5):
if i == 10:
break
else:
print('Loop completed without break')
PYTHON
#3.2
Q2:
What is the danger of using a mutable default argument in Python?
Ans:
Default argument values are evaluated only once when the function is defined, so using a mutable object (like a list or dict) as a default can cause it to be shared and unexpectedly modified across multiple calls.
Code Example
def add_item(item, items=[]): # BUG: shared list
items.append(item)
return items
PYTHON
#3.3
Q3:
How do you write a decorator that accepts arguments?
Ans:
You need an additional outer function that accepts the decorator's arguments and returns the actual decorator function, which in turn wraps the target function.
Code Example
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hi():
print('Hi')
PYTHON
#3.4
Q4:
What does functools.wraps do?
Ans:
functools.wraps is a decorator used inside custom decorators to preserve the original function's metadata (like __name__ and __doc__) on the wrapper function, which would otherwise be overwritten.
Code Example
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
PYTHON
#3.5
Q5:
What is the maximum recursion depth in Python and how can you change it?
Ans:
Python has a default recursion limit (typically 1000) to prevent stack overflow from infinite recursion, which can be adjusted using sys.setrecursionlimit(), though increasing it too much risks crashing the interpreter.
Code Example
import sys
sys.setrecursionlimit(2000)
PYTHON
#3.6
Q6:
What is the difference between pass by value and pass by reference in Python function calls?
Ans:
Python uses 'pass by object reference': mutable objects passed to a function can be modified in place affecting the caller, while reassigning the parameter to a new object inside the function does not affect the caller's original reference.
Code Example
def modify(lst):
lst.append(4) # affects caller's list
lst = [9,9,9] # does not affect caller's reference
my_list = [1,2,3]
modify(my_list) # my_list becomes [1,2,3,4]
PYTHON
#3.7
Q7:
What is the Method Resolution Order (MRO) in Python?
Ans:
MRO defines the order in which base classes are searched when executing a method, determined by the C3 linearization algorithm; it can be inspected using ClassName.__mro__ or ClassName.mro().
PYTHON
#3.8
Q8:
Why should you define __hash__ when overriding __eq__?
Ans:
If a class overrides __eq__, Python sets __hash__ to None by default, making instances unhashable; if the objects need to be used in sets or as dict keys, __hash__ must be explicitly defined consistently with __eq__.
PYTHON
#3.9
Q9:
What is name mangling in Python?
Ans:
Name mangling automatically renames attributes prefixed with double underscores (like __value) to _ClassName__value internally, helping avoid accidental name clashes in subclasses rather than providing true access restriction.
Code Example
class Base:
def __init__(self):
self.__secret = 42 # becomes _Base__secret
PYTHON
#3.10
Q10:
What is a class's __slots__ attribute used for?
Ans:
__slots__ restricts the set of attributes an instance can have, preventing creation of a per-instance __dict__ and reducing memory usage, useful when creating many instances of a simple class.
Code Example
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
PYTHON
#3.11
Q11:
What is a metaclass in Python?
Ans:
A metaclass is the 'class of a class', controlling how classes themselves are created; by default this is type, but custom metaclasses can customize class creation behavior, commonly used in advanced frameworks.
Code Example
class Meta(type):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
PYTHON
#3.12
Q12:
What is the purpose of the __call__ method?
Ans:
__call__ allows an instance of a class to be invoked like a function using parentheses, enabling objects to behave as callables.
Code Example
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
triple = Multiplier(3)
print(triple(5)) # 15
PYTHON
#3.13
Q13:
What is exception chaining in Python using 'raise ... from ...'?
Ans:
The 'raise NewException() from original_exception' syntax explicitly links a new exception to the one that caused it, preserving context and making the traceback clearer when re-raising a different exception type.
Code Example
try:
int('abc')
except ValueError as e:
raise RuntimeError('Conversion failed') from e
PYTHON
#3.14
Q14:
How do you write a custom context manager using a class?
Ans:
You implement __enter__ (returning the resource, run at the start of the with block) and __exit__ (handling cleanup and optionally suppressing exceptions, run at the end).
Code Example
class Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f'Elapsed: {time.time() - self.start}')
PYTHON
#3.15
Q15:
How do you write a context manager using a generator and the contextlib module?
Ans:
The @contextlib.contextmanager decorator lets you write a context manager as a generator function, using yield to separate setup code (before yield) from teardown code (after yield).
Code Example
from contextlib import contextmanager
@contextmanager
def timer():
start = time.time()
yield
print(f'Elapsed: {time.time() - start}')
PYTHON
#3.16
Q16:
What does the yield from statement do?
Ans:
yield from delegates iteration to a sub-generator or other iterable, yielding all of its values directly, simplifying code that would otherwise require an explicit loop to forward each value.
Code Example
def inner():
yield 1
yield 2
def outer():
yield from inner()
yield 3
PYTHON
#3.17
Q17:
How do you create a custom iterable class in Python?
Ans:
You implement __iter__ (returning an iterator object, often self) and __next__ (returning the next item or raising StopIteration when done) on your class.
Code Example
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
PYTHON
#3.18
Q18:
What is the Global Interpreter Lock (GIL) in Python?
Ans:
The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time, even on multi-core systems, which limits true parallelism for CPU-bound multithreaded code but doesn't affect I/O-bound concurrency as much.
PYTHON
#3.19
Q19:
What is the difference between multithreading and multiprocessing in Python?
Ans:
Multithreading runs multiple threads within a single process sharing memory, but is limited by the GIL for CPU-bound tasks, while multiprocessing runs separate processes each with its own Python interpreter and memory space, achieving true parallelism for CPU-bound work at the cost of higher overhead.
PYTHON
#3.20
Q20:
When should you use multiprocessing instead of multithreading in Python?
Ans:
Multiprocessing is preferred for CPU-bound tasks that need true parallel execution across cores, since it bypasses the GIL, while multithreading is more suitable for I/O-bound tasks (like network requests or file operations) where threads spend most of their time waiting.
PYTHON
#3.21
Q21:
What is the difference between async/await and threading in Python?
Ans:
async/await uses a single-threaded event loop with cooperative multitasking, where tasks explicitly yield control at await points, while threading uses OS-level preemptive multitasking across multiple threads, subject to the GIL for CPU-bound work.
PYTHON
#3.22
Q22:
What is a race condition and how can you prevent it in Python threads?
Ans:
A race condition occurs when multiple threads access and modify shared data concurrently, producing unpredictable results; it can be prevented using synchronization primitives like threading.Lock to ensure exclusive access to shared resources.
Code Example
lock = threading.Lock()
with lock:
shared_counter += 1
PYTHON
#3.23
Q23:
What is a reference cycle and how does Python handle it?
Ans:
A reference cycle occurs when two or more objects reference each other, preventing their reference counts from reaching zero even when they're unreachable from the rest of the program; Python's generational garbage collector (gc module) periodically detects and collects these cycles.
PYTHON
#3.24
Q24:
What are Python's memory optimization techniques like interning?
Ans:
Python caches small integers (-5 to 256) and some string literals so that multiple references to the same value point to the same object in memory, reducing memory usage and improving comparison speed for common ones.
PYTHON
#3.25
Q25:
What is functools.singledispatch used for?
Ans:
singledispatch allows a function to have different implementations based on the type of its first argument, effectively simulating single-argument type-based overloading in Python.
Code Example
from functools import singledispatch
@singledispatch
def process(arg):
print('default')
@process.register
def _(arg: int):
print('int handler')
PYTHON
#3.26
Q26:
What is the difference between deepcopy and copy.copy for functions with default arguments?
Ans:
This is unrelated to defaults directly, but copy.copy() creates a shallow copy sharing nested references, while copy.deepcopy() recursively duplicates all nested objects; using deepcopy avoids unintentionally shared mutable state between copies.
PYTHON
#3.27
Q27:
What is currying in the context of Python functions?
Ans:
Currying transforms a function taking multiple arguments into a sequence of functions each taking a single argument; Python doesn't support it natively but it can be implemented manually or via functools.partial.
PYTHON
#3.28
Q28:
What is the difference between deepcopy of an object and pickling/unpickling it?
Ans:
Both can produce an independent copy of complex nested objects, but deepcopy operates purely in memory and works with more object types directly, while pickling serializes to bytes (useful for storage or transfer) and requires objects to be picklable.
PYTHON
#3.29
Q29:
What is monkey patching in Python?
Ans:
Monkey patching is dynamically modifying or extending a class or module's attributes/methods at runtime, often used in testing or to patch third-party code, though it can make code harder to understand and maintain if overused.
Code Example
import module
module.some_function = lambda: 'patched'
PYTHON
#3.30
Q30:
What is the __new__ method and how does it differ from __init__?
Ans:
__new__ is a static method responsible for creating and returning a new instance (called before __init__), while __init__ initializes the already-created instance's attributes; __new__ is rarely overridden except for immutable types or metaclass-related patterns.
Code Example
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
PYTHON
#3.31
Q31:
What is the difference between a shallow interface and Python's protocol typing (structural typing)?
Ans:
Python's typing.Protocol (PEP 544) enables structural typing, where an object is considered compatible with a type if it has the required methods/attributes, regardless of explicit inheritance, aligning with duck typing but allowing static type checkers to verify it.
Code Example
from typing import Protocol
class Sized(Protocol):
def __len__(self) -> int: ...
PYTHON
#3.32
Q32:
What is the purpose of the __del__ method?
Ans:
__del__ is called when an object is about to be garbage collected, sometimes used for cleanup, but its exact timing is not guaranteed (especially with reference cycles), so context managers are generally preferred for reliable resource cleanup.
PYTHON
#3.33
Q33:
What is the difference between shallow scoping in list comprehensions across Python 2 and 3?
Ans:
In Python 3, the loop variable in a list comprehension is scoped locally to the comprehension itself and doesn't leak into the enclosing scope, unlike in Python 2 where it did leak and could overwrite existing variables.
PYTHON
#3.34
Q34:
What is the GIL's impact on I/O-bound versus CPU-bound multithreaded programs?
Ans:
The GIL is released during blocking I/O operations, so I/O-bound multithreaded programs can still achieve good concurrency, while CPU-bound multithreaded programs see little to no speedup from multiple threads since only one thread executes Python bytecode at a time.
PYTHON
#3.35
Q35:
What is the difference between iter(obj) and iter(callable, sentinel)?
Ans:
iter(obj) returns an iterator from an iterable object, while the two-argument form iter(callable, sentinel) repeatedly calls the callable, yielding its results until the sentinel value is returned, at which point iteration stops.
PYTHON
#3.36
Q36:
What is a context variable and when might contextvars be used?
Ans:
The contextvars module provides context-local state that works correctly across async tasks and threads, useful for tracking per-request data (like a request ID) in asynchronous web applications without relying on thread-local storage.
PYTHON
#3.37
Q37:
What is the difference between Python's == operator behavior for lists versus tuples containing the same elements?
Ans:
Both lists and tuples compare element-wise for equality with ==, so a list and tuple with identical elements in the same order compare as unequal only because their types differ, not their contents; comparing list == tuple with same elements returns False due to differing types, but list == list or tuple == tuple with matching contents returns True.