Python Interview Questions and Answers
Core language, data structures, comprehensions, decorators and async programming.
Whether you are preparing for entry-level Python interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.
1 What is a generator and when should you use one? Medium
A generator is a function that yields values lazily using yield. Calling it returns a generator object that produces items on demand and remembers its position, so memory stays O(1) instead of materialising the whole sequence.
def read_lines(path):
with open(path) as f:
for line in f:
yield line.strip()
# process a huge file without loading it all into memory
for line in read_lines('big.log'):
...
Use generators for streaming data, pipelines and infinite sequences. They are also the foundation of async, where an async generator yields with async for.
2 Explain decorators with a practical example. Medium
A decorator is a callable that takes a function and returns a new one, adding behaviour without changing the original code. The @decorator syntax is sugar for func = decorator(func).
import functools, time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f'{func.__name__} took {time.perf_counter() - start:.3f}s')
return result
return wrapper
@timed
def train():
...
Real uses: logging, authentication, caching, retries, rate limiting. functools.wraps preserves the wrapped function's metadata. Decorators with arguments need an extra layer of nesting.
3 What is pickling and unpickling? Medium
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
4 How Python is interpreted? Medium
Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
5 How memory is managed in Python? Medium
Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
6 What are the tools that help to find bugs or perform static analysis? Medium
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
7 What are Python decorators? Medium
A decorator in Python is a design pattern that dynamically alters or extends the behavior of a function or class without permanently modifying its source code. In Python, decorators are higher-order functions that accept a callable and return an enhanced callable:
### How Decorators Work:
import functools
import time
def timer_decorator(func):
@functools.wraps(func) # Preserves function metadata (__name__, __doc__)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
execution_time = time.perf_counter() - start_time
print(f"[{func.__name__}] executed in {execution_time:.4f} seconds")
return result
return wrapper
@timer_decorator
def process_data(records):
time.sleep(0.1)
return len(records)
### Common Production Use Cases:
- Authentication & Authorization:
@login_required,@roles_allowed(['admin'])in Django and Flask. - Caching / Memoization:
@functools.lru_cache(maxsize=128)for expensive computations. - Rate Limiting & Retries: Automatically retrying network requests upon transient failure.
- Logging & Metrics Instrumentation: Emitting OpenTelemetry traces or Prometheus metrics around API calls.
8 What is the difference between list and tuple? Medium
Both lists and tuples are ordered sequence collections in Python, but they differ fundamentally in mutability, memory allocation, and intended design use:
| Feature | list | tuple |
| :--- | :--- | :--- |
| Mutability | Mutable (elements can be added, updated, or removed in place) | Immutable (fixed size and contents after creation) |
| Syntax | Square brackets: [1, 2, 3] | Parentheses: (1, 2, 3) |
| Memory Allocation | Over-allocates memory buffer to allow dynamic resizing | Compact, fixed-size contiguous memory block |
| Iteration Performance | Slightly slower iteration and creation overhead | Faster creation and iteration |
| Hashability | Unhashable (cannot be used as dictionary key or set item) | Hashable (can be dictionary key if all elements are hashable) |
| Idiomatic Usage | Homogeneous collections that grow or shrink | Heterogeneous records, fixed coordinate tuples (x, y) |
### Memory Benchmark Example:
import sys
l = [1, 2, 3, 4, 5]
t = (1, 2, 3, 4, 5)
print(sys.getsizeof(l)) # ~104 bytes (due to resizing buffer)
print(sys.getsizeof(t)) # ~80 bytes (exact compact allocation)
9 How are arguments passed by value or by reference? Medium
Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.
10 What is Dict and List comprehensions are? Medium
List and Dictionary comprehensions provide a concise, declarative syntax to construct new lists and dictionaries from existing iterables:
### 1. List Comprehension:
Syntax: [expression for item in iterable if condition]
# Traditional approach
squares = []
for x in range(10):
if x % 2 == 0:
squares.append(x ** 2)
# Comprehension equivalent (faster & cleaner)
squares = [x ** 2 for x in range(10) if x % 2 == 0]
# Result: [0, 4, 16, 36, 64]
### 2. Dictionary Comprehension:
Syntax: {key_expr: value_expr for item in iterable if condition}
users = [("alice", 28), ("bob", 34), ("carol", 22)]
adult_map = {username: age for username, age in users if age >= 25}
# Result: {'alice': 28, 'bob': 34}
### Why Comprehensions Are Preferred:
Comprehensions execute at C-level speed in CPython, bypassing the overhead of repeated Python bytecode LIST_APPEND instructions, while producing readable and expressive code.
11 What are the built-in type does Python provides? Medium
There are mutable and Immutable types of Pythons built in types Mutable built-in types
List Sets
Dictionaries Immutable built-in types
Strings Tuples Numbers
12 What is namespace in Python? Medium
In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.
13 What is lambda in Python? Medium
A lambda function in Python is a small, anonymous (unnamed) function defined using the lambda keyword:
### Syntax:lambda arguments: expression
# Simple lambda
multiply = lambda x, y: x * y
print(multiply(4, 5)) # Output: 20
# Practical usage as a sorting key
students = [('Alice', 88), ('Bob', 95), ('Charlie', 78)]
students.sort(key=lambda item: item[1], reverse=True)
# Result: [('Bob', 95), ('Alice', 88), ('Charlie', 78)]
### Key Constraints:
- A lambda function can accept any number of positional or keyword arguments.
- It can contain only a single expression, which is automatically evaluated and returned.
- It cannot contain statements (no
return,pass,assert,try/except, or assignments). - *PEP 8 Guidance:* Do not assign lambdas to variable names (
f = lambda x: x); define a standarddeffunction instead for proper stack trace debugging.
14 Why lambda forms in Python does not have statements? Medium
Python creator Guido van Rossum deliberately designed Python lambda expressions to be restricted to a single expression rather than containing full statements:
### Key Reasons:
- Grammar & Indentation Alignment:
Python's syntax relies fundamentally on indentation to delimit statement blocks. Allowing multi-line statements (like if/else, loops, or try/except) inside a lambda expression would introduce syntactic ambiguity when nested inside expressions, parentheses, or argument lists.
- Encouraging Clean Code Architecture:
Lambdas were intended strictly for small, disposable inline callbacks (such as passing a key function to sorted() or map()). If a function requires complex statements, exception handling, or multiple lines of logic, defining an explicit named function using def improves readability, allows docstrings, and ensures meaningful function names appear in stack traces.
15 What is pass in Python? Medium
Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.
16 In Python what are iterators? Medium
An iterator in Python is an object that represents a stream of data. It implements the Python Iterator Protocol, which consists of two core magic methods:
__iter__(): Returns the iterator object itself.__next__(): Returns the next item from the sequence. When no elements remain, it raises theStopIterationexception.
### Custom Iterator Example:
class CountUpTo:
def __init__(self, max_value):
self.max_value = max_value
self.current = 1
def __iter__(self):
return self
def __next__(self):
if self.current <= self.max_value:
val = self.current
self.current += 1
return val
raise StopIteration
counter = CountUpTo(3)
for num in counter:
print(num) # Prints 1, 2, 3
### Iterable vs Iterator:
- An Iterable is any object that can return an iterator via
iter(obj)(e.g. lists, tuples, dicts, strings). - An Iterator is the stateful helper that actually produces values one at a time via
next(it).
17 What is unit test in Python? Medium
A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc.
18 In Python what is slicing? Medium
Slicing is a Python mechanism for extracting a sub-sequence from a sequence data type (such as a list, tuple, or str) using extended indexing notation:
### Syntax:sequence[start:stop:step]
start: Zero-based beginning index (inclusive). Defaults to 0.stop: Ending index (exclusive). Defaults to sequence length.step: Stride / increment value between indices. Defaults to 1.
### Practical Examples:
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(data[2:6]) # [2, 3, 4, 5] (sublist from index 2 to 5)
print(data[:4]) # [0, 1, 2, 3] (first 4 items)
print(data[6:]) # [6, 7, 8, 9] (from index 6 to end)
print(data[::2]) # [0, 2, 4, 6, 8] (every second item)
print(data[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reverse copy)
Slicing creates a new shallow copy of the requested elements without modifying the original sequence.
19 What are generators in Python? Medium
Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.
Let's try and build a generator for fibonacci numbers –
## generate fibonacci numbers upto n
def fib(n):
p, q = 0, 1
while(p < n):
yield p
p, q = q, p + q
x = fib(10) # create generator object
## iterating using __next__(), for Python2, use next()
x.__next__() # output => 0
x.__next__() # output => 1
x.__next__() # output => 1
x.__next__() # output => 2
x.__next__() # output => 3
x.__next__() # output => 5
x.__next__() # output => 8
x.__next__() # error
## iterating using loop
for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8
20 What Is Docstring In Python? Medium
A docstring is a unique text that happens to be the first statement in the following Python constructs:
Module, Function, Class, or Method def inition.
A docstring gets added to the __doc__ attribute of the string object.
21 How can you copy an object in Python? Medium
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
22 What is negative index in Python? Medium
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
23 How you can convert a number to a string? Medium
In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
24 What is the difference between Xrange and range? Medium
The distinction between range and xrange was a landmark difference between Python 2 and Python 3:
### Historical Context:
- In Python 2:
range(n)eagerly created and allocated a physical list ofnintegers in memory. Forrange(10000000), this consumed hundreds of megabytes of RAM.xrange(n)returned an on-demand generator/sequence object that computed numbers lazily without allocating a giant list.- In Python 3:
xrangewas completely removed.- The Python 3
rangeobject adopted the lazy, memory-efficient behavior of Python 2'sxrange.
### Modern Python 3 range:
In Python 3, range(1000000) consumes constant $O(1)$ memory regardless of size because it computes values on the fly:
import sys
r = range(1_000_000_000)
print(sys.getsizeof(r)) # Only 48 bytes!
25 What is module and package in Python? Medium
In Python, module is the way to structure program. Each Python program file is a module, which import s other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
26 Mention what are the rules for local and global variables in Python? Medium
Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly global.
27 How can you share global variables across modules? Medium
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
28 Explain how can you make a Python Script executable on Unix?To make a Python Script executable on Unix, you need to do two things,? Medium
To convert a Python script into an executable command-line program on Unix/Linux/macOS systems, two steps are required:
### Step 1: Add the Shebang Line
Add a shebang directive as the very first line of your script to tell the Unix shell which interpreter to invoke:
#!/usr/bin/env python3
import sys
def main():
print(f"Running on Python {sys.version.split()[0]}")
if __name__ == "__main__":
main()
*Why #!/usr/bin/env python3?* Using /usr/bin/env dynamically locates the Python 3 interpreter in the user's active $PATH (including virtual environments), making the script portable across Linux, macOS, and BSD systems.
### Step 2: Grant Execution Permissions
Run chmod +x in your terminal to grant execute permissions to the file:
chmod +x my_script.py
You can now run your script directly without typing python3:
./my_script.py
29 Explain how to delete a file in Python? Medium
In Python, file deletion is performed using either the modern pathlib module (recommended) or the traditional os module:
### 1. Using pathlib (Modern & Idiomatic):
from pathlib import Path
file_path = Path("temp_log.txt")
# Safe deletion using missing_ok=True (Python 3.8+)
file_path.unlink(missing_ok=True)
### 2. Using the os Module:
import os
file_to_delete = "temp_log.txt"
if os.path.exists(file_to_delete):
os.remove(file_to_delete) # or os.unlink(file_to_delete)
else:
print(f"File '{file_to_delete}' does not exist.")
### Deleting Directories:
- For empty directories:
os.rmdir("empty_folder")orPath("empty_folder").rmdir(). - For recursive directory trees with contents: Use
shutil.rmtree("target_folder").
30 Explain how can you generate random numbers in Python? Medium
To generate random numbers in Python, you need to import command as import random
random.random()
This return s a random floating point number in the range [0,1)
31 Explain how can you access a module written in Python from C? Medium
Python can be embedded inside C/C++ applications using the official Python C API (Python.h).
### Standard Steps to Import and Invoke Python from C:
#include <Python.h>
int main(int argc, char *argv[]) {
// 1. Initialize Python runtime interpreter
Py_Initialize();
// 2. Add current directory to sys.path so the module can be located
PyRun_SimpleString("import sys; sys.path.append('.')");
// 3. Import the Python module (e.g. 'my_math')
PyObject *pName = PyUnicode_DecodeFSDefault("my_math");
PyObject *pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
// 4. Retrieve a specific function from the module
PyObject *pFunc = PyObject_GetAttrString(pModule, "calculate_tax");
if (pFunc && PyCallable_Check(pFunc)) {
// 5. Call the function with arguments
PyObject *pArgs = PyTuple_Pack(1, PyFloat_FromDouble(50000.0));
PyObject *pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result: %f\n", PyFloat_AsDouble(pValue));
Py_DECREF(pValue);
}
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
// 6. Clean up interpreter memory
Py_Finalize();
return 0;
}
32 Mention the use of // operator in Python? Medium
It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
33 Mention the use of the split function in Python? Medium
The use of the split function in Python is that it breaks a string into shorter strings using the def ined separator. It gives a list of all words present in the string.
34 Explain what is Flask & its benefits? Medium
Flask is a web micro framework for Python based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug and jingja are two of its dependencies.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.
35 Mention what is the difference between Django, Pyramid, and Flask? Medium
Flask is a "micro framework" primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.
Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
Like Pyramid, Django can also used for larger applications. It includes an ORM.
36 Mention what is Flask-WTF and what are their features? Medium
Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are
Integration with wtforms Secure form with csrf token Global csrf protection Internationalization integration Recaptcha supporting
File upload that works with Flask Uploads
37 Explain what is the common way for the Flask script to work? Medium
A standard Flask application operates as a WSGI (Web Server Gateway Interface) micro-framework that maps incoming HTTP URLs to Python view functions:
### Standard Architectural Flow:
- Application Instance: Instantiate
Flask(__name__)to initialize static asset paths and template directories. - Route Decorators: Use
@app.route('/path', methods=['GET', 'POST'])to register URL endpoints in the Werkzeug URL map. - Request Lifecycle: When a client sends an HTTP request, Flask pushes a request context (
requestglobal proxy) containing headers, cookies, query parameters, and JSON payloads. - View Function Execution: The matching function processes business logic, interacts with a database, and returns a response string, JSON via
jsonify(), or rendered Jinja2 template viarender_template(). - WSGI Server Deployment: In production, Flask is served by production WSGI servers like Gunicorn or uWSGI sitting behind an Nginx reverse proxy:
gunicorn -w 4 -b 0.0.0.0:8000 app:app
38 Explain how you can access sessions in Flask? Medium
A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
39 Is Flask an MVC model and if yes give an example showing MVC pattern for your application? Medium
Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example
from flask import Flaskapp = Flask(_name_)
@app.route("/")
Def hello():
return "Hello World"
app.run(debug = True)
In this code your,
Configuration part will be
from flask import Flask
app = Flask(_name_)
View part will be
@app.route("/")
Def hello():
return "Hello World"
While you model or main part will be
app.run(debug = True)
40 What type of a language is Python? Interpreted or Compiled? Medium
Beginner's Answer:
Python is an interpreted, interactive, objectoriented programming language.
Expert Answer:
Python is an interpreted language, as opposed to a compiled one, though the
distinction can be blurry because of the presence of the bytecode compiler. This means
that source files can be run directly without explicitly creating an executable which is
then run.
41 What do you mean by Python being an "interpreted language"? (Continues from previous question)? Medium
An interpreted languageis a programming languagefor which most of its
implementations execute instructions directly, without previously compiling a program
into machinelanguageinstructions. In context of Python, it means that Python program
runs directly from the source code.
42 Please provide an example implementation of a function called "my_func" that returns the square of a given variable "x". (Continues from previous question)? Medium
An example implementation of my_func returning the square of a given number x:
def my_func(x):
return x ** 2
# Example:
print(my_func(5)) # Output: 25
43 Is Python statically typed or dynamically typed? Medium
Dynamic.
In a statically typed language, the type of variables must be known (and usually
declared) at the point at which it is used. Attempting to use it will be an error. In a
dynamically typed language, objects still have a type, but it is determined at runtime.
You are free to bind names (variables) to different objects with a different type. So long
as you only perform operations valid for the type the interpreter doesn't care what type
they actually are.
44 Is Python strongly typed or weakly typed language? Medium
Strong.
In a weakly typed language a compiler / interpreter will sometimes change the
type of a variable. For example, in some languages (like JavaScript) you can add
strings to numbers 'x' + 3 becomes 'x3'. This can be a problem because if you have
made a mistake in your program, instead of raising an exception execution will continue
but your variables now have wrong and unexpected values. In a strongly typed
language (like Python) you can't perform operations inappropriate to the type of the
object attempting to add numbers to strings will fail. Problems like these are easier to
diagnose because the exception is raised at the point where the error occurs rather than
at some other, potentially far removed, place.
45 Create a unicode string in Python with the string "This is a test string"? Medium
In modern Python 3, all strings are Unicode by default (str type represents Unicode code points encoded in UTF-8):
# In Python 3, this is already a native Unicode string:
text = "This is a test string"
print(type(text)) # <class 'str'>
# Unicode escape characters are natively supported:
unicode_text = "This is a test string: ✅ 😀"
print(unicode_text) # Output: This is a test string: ✅ 😀
### Historical Python 2 Comparison:
In legacy Python 2, strings were ASCII byte sequences by default and required an explicit u prefix (u"This is a test string") to create Unicode objects. In Python 3, byte sequences are explicitly declared with b"byte string" and decoded to Unicode via b_str.decode('utf-8').
46 What is the Python syntax for switch case statements? Medium
Starting in Python 3.10, Python natively introduced the match / case statement (PEP 634 Structural Pattern Matching):
### Modern Python 3.10+ Pattern Matching:
def http_status_handler(status_code: int) -> str:
match status_code:
case 200:
return "OK"
case 301 | 302: # Or pattern matching
return "Redirect"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _: # Wildcard pattern (equivalent to default)
return "Unknown Status Code"
### Pre-Python 3.10 Alternatives:
Before Python 3.10, developers implemented switch-case logic using dictionary dispatch maps:
dispatch_table = {
200: lambda: "OK",
404: lambda: "Not Found"
}
result = dispatch_table.get(status_code, lambda: "Unknown")()
47 What is a lambda statement? Provide an example. Medium
A lambda statement is used to create new function objects and then return them at
runtime. Example:
my_func=lambdax:x**2
creates a function called my_func that return s the square of the argument
passed.
48 What are the rules for local and global variables in Python? Medium
If a variable is def ined outside function then it is implicitly global. If variable is
assigned new value inside the function means it is local. If we want to make it global we
need to explicitly def ine it as global. Variable referenced inside the function are implicit
global
49 What is the output of the following Python program regarding local variable shadowing? Medium
#!/usr/bin/python
def fun1(a):
print'a:',a
a=33;
print'locala:',a
a=100
fun1(a)
print'aoutsidefun1:',a
Output:
a:100
locala:33
aoutsidefun1:100
50 What is the output of the following Python program using global variable modification? Medium
#!/usr/bin/python
def fun2():
globalb
print'b:',b
b=33
print'globalb:',b
b=100
fun2()
print'boutsidefun2′,b
Ans. Output:
b:100
globalb:33
boutsidefun2:33
51 What is the output of the following Python program with variable swapping and globals? Medium
#!/usr/bin/python
def foo(x,y):
globala
a=42
x,y=y,x
b=33
b=17
c=100
print(a,b,x,y)
a,b,x,y=1,15,3,4
foo(17,4)
print(a,b,x,y)
Ans.Output:
4217417
421534
52 What is the output of the following Python program demonstrating mutable default arguments? Medium
### The Code Snippet:
def foo(x=[]):
x.append(1)
return x
print(foo())
print(foo())
### Output:
[1]
[1, 1]
### Technical Explanation:
In Python, default argument expressions are evaluated once at function definition time, not each time the function is called.
Because Python lists are mutable objects, the default parameter x references a single list stored in the function's __defaults__ attribute. Subsequent invocations that omit argument x continue modifying this same in-memory list object.
### The Idiomatic Production Fix:
Always use None as the default argument sentinel value:
def foo(x=None):
if x is None:
x = []
x.append(1)
return x
53 What is the purpose of #!/usr/bin/Pythonon the first line in the above code? Is there any advantage? Medium
By specifying #!/usr/bin/pythonyou specify exactly which interpreter will be
used to run the script on a particular system. This is the hardcoded path to the python
interpreter for that particular system. The advantage of this line is that you can use a
specific python version to run your code.
54 What is the output of indexing a list out of range in Python? Medium
### Code Snippet:
items = ['a', 'b', 'c', 'd', 'e']
print(items[10])
### Output:
Python raises an IndexError:
IndexError: list index out of range
### Key Differences with Slicing:
While direct indexing (items[10]) raises an IndexError when the index exceeds bounds, slicing does not raise an error:
print(items[10:15]) # Returns empty list [] without raising an exception
### Safe Retrieval in Production:
To safely access items without crashing from an IndexError:
idx = 10
item = items[idx] if idx < len(items) else None
55 What is the output of slicing a list beyond its length in Python? Medium
list=['a','b','c','d','e']
printlist[10:]
Ans. Output:
[]
Theabovecodewilloutput[],andwillnotresultinanIndexError.
As one would expect, attempting to access a member of a list using an index that
exceeds the number of members results in an IndexError.
56 What does this list comprehension do:? Medium
### Expression:
[x**2 for x in range(10) if x % 2 == 0]
### What It Does:
This list comprehension iterates through the numbers 0 through 9, filters for even numbers using the condition x % 2 == 0, and calculates the square (x ** 2) of each matching number:
range(10)generates:0, 1, 2, 3, 4, 5, 6, 7, 8, 9if x % 2 == 0filters for:0, 2, 4, 6, 8x2transforms them into:02=0,22=4,42=16,62=36,82=64
### Final Result:
[0, 4, 16, 36, 64]
57 Do sets, dictionaries and tuples also support comprehensions? Medium
Sets and dictionaries support it. However tuples are immutable and have
generators but not comprehensions.
Set Comprehension:
r={xforxinrange(2,101)
ifnotany(x%y==0foryinrange(2,x))}
Dictionary Comprehension:
{i:jfori,jin{1:'a',2:'b'}.items()}
since
{1:'a',2:'b'}.items()return salistof2-Tuple.iisthefirstelement
oftuplejisthesecond.
58 What are some mutable and immutable datatypes/datastructures in Python? Medium
In Python's object model, every object has a type, value, and identity. Whether its internal value can change without creating a new identity determines its mutability:
### 1. Mutable Data Types (Can be altered in place):
list: Dynamic arrays ([1, 2, 3]).dict: Key-value hash tables ({'key': 'value'}).set: Unordered collections of unique items ({1, 2, 3}).bytearray: Mutable sequences of bytes.- Custom Classes: By default, user-defined class instances are mutable unless decorated with
@dataclass(frozen=True).
### 2. Immutable Data Types (Cannot be modified after instantiation):
int,float,complex: Numeric types.bool:TrueandFalse.str: Textual strings ("hello").tuple: Fixed sequences ((1, 2, 3)).frozenset: Immutable hashable sets.bytes: Immutable byte sequences.
### Architectural Impact:
Only immutable objects are hashable and can serve as dictionary keys or elements of a set.
59 What can you use Python generator functions for? Medium
One of the reasons to use generator is to make the solution clearer for some kind
of solutions.
The other is to treat results one at a time, avoiding building huge lists of results that you
would process separated anyway.
60 When is not a good time to use Python generators? Medium
Use list instead of generator when:
1 You need to access the data multiple times (i.e. cache the results instead of
recomputing them)
2 You need random access (or any access other than forward sequential order):
3 You need to join strings (which requires two passes over the data)
4 You are using PyPy which sometimes can't optimize generator code as much
as it can with normal function calls and list manipulations.
61 What's your preferred text editor? Medium
In professional Python software engineering, the choice of IDE or text editor focuses on productivity, type inference, debugging capabilities, and ecosystem integration:
### Leading Python Development Environments:
- VS Code (Visual Studio Code):
- The most widely used editor in the Python community.
- Key highlights: Microsoft Python extension, Pylance type checker, integrated interactive Jupyter notebooks, Git source control, and remote container development (
devcontainers).
- PyCharm (JetBrains):
- Dedicated Python IDE with powerful refactoring tools, database navigation, Django/Flask framework tooling, and visual test runners.
- Neovim / Vim:
- Preferred by terminal power users who prioritize modal editing, ultra-fast startup times, and tailored keyboard workflows.
### What Interviewers Are Assessing:
This question evaluates whether you know your development tools deeply:
- Can you configure linters (Ruff, Flake8) and formatters (Black)?
- Do you use visual breakpoints and interactive debuggers (
pdb, IDE debuggers) instead of solely relying onprint()? - Are you comfortable working in collaborative team codebases with shared editor settings?
62 When should you use generator expressions vs. list comprehensions in Python and vice-versa? Medium
Iterating over the generator expression or the list comprehension will do the same
thing. However, the list comp will create the entire list in memory first while the
generator expression will create the items on the fly, so you are able to use it for very
large (and also infinite!) sequences.
63 What is a negative index in Python? Medium
Python arrays and list items can be accessed with positive or negative numbers. A
negative Index accesses the elements from the end of the list counting backwards.
Example:
a=[123]
printa[-3]
printa[-2]
Outputs:
1
2
64 What is the difference between range and xrange functions? Medium
Range return s a list while xrange return s an xrange object which take the
same memory no matter of the range size. In the first case you have all items already
generated (this can take a lot of time and memory). In Python 3 however, range is
implemented with xrange and you have to explicitly call the list function if you want to
convert it to a list.
65 How can I find methods or attributes of an object in Python? Medium
Builtin dir() function of Python ,on an instance shows the instance variables as
well as the methods and class attributes def ined by the instance's class and all its base
classes alphabetically. So by any object as argument to dir() we can find all the
methods & attributes of the object's class
66 What is the statement that can be used in Python if a statement is required syntactically but the program requires no action? Medium
The pass statement in Python is a null statement (no-op). When executed, nothing happens. It is used as a syntactic placeholder where code is required but no action needs to be taken (e.g., in empty classes, functions, or exception handling blocks).
67 Do you know what is the difference between lists and tuples? Can you give me an example for their usage? Medium
First list are mutable while tuples are not, and second tuples can be hashed e.g.
to be used as keys for dictionaries. As an example of their usage, tuples are used when
the order of the elements in the sequence matters e.g. a geographic coordinates, "list"
of points in a path or route, or set of actions that should be executed in specific order.
Don't forget that you can use them a dictionary keys. For everything else use lists
68 What is the function of "self"? Medium
Self is a variable that represents the instance of the object to itself. In most of the object oriented programming language, this is passed to the methods as a hidden parameters that is def ined by an object. But, in python, it is declared and passed explicitly. It is the first argument that gets created in the instance of the class A and the parameters to the methods are passed automatically. It refers to separate instance of the variable for individual objects.
Let's say you have a class ClassA which contains a method methodA def ined as:
def methodA(self, arg1, arg2): #do something
and ObjectA is an instance of this class.
Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:
ClassA.methodA(ObjectA, arg1, arg2)
The self variable refers to the object itself.
69 How is memory managed in Python? Medium
Memory management in Python involves a private heap containing all
Python objects and data structures. Interpreter takes care of Python heap and
the programmer has no access to it. The allocation of heap space for Python
objects is done by Python memory manager. The core API of Python provides
some tools for the programmer to code reliable and more robust program. Python
also has a builtin garbage collector which recycles all the unused memory.
The gc module def ines functions to enable /disable garbage collector:
gc.enable() Enables automatic garbage collection.
gc.disable()-Disables automatic garbage collection
70 What is __init__.py? Medium
The __init__.py file indicates that the directory containing it should be treated as a regular Python package namespace.
### Key Functions of __init__.py:
- Package Initialization: Any code placed inside
__init__.pyexecutes automatically when the package is imported (import my_package). - Export API Control (
__all__): Defines what symbols are exported when a consumer executesfrom my_package import *:
# my_package/__init__.py
from .client import APIClient
from .exceptions import APIError
__all__ = ["APIClient", "APIError"]
- Python 3.3+ Namespace Packages:
Since Python 3.3 (PEP 420), directories without __init__.py are treated as implicit namespace packages (allowing packages to be split across different directories). However, adding an explicit __init__.py remains standard industry best practice for regular packages.
71 Print contents of a file ensuring proper error handling? Medium
try:
withopen('filename','r')asf:
printf.read()
exceptIOError:
print"Nosuchfileexists"
75 How do we share global variables across modules in Python?
We can create a config file and store the entire global variable to be
shared across modules in it. By simply import ing config, the entire global variable
def ined will be available for use in other modules.
For example I want a, b & c to share between modules.
config.py :
a=0
b=0
c=0
module1.py:
import config
config.a=1
config.b=2
config.c=3
print"a,b&resp.are:",config.a,config.b,config.c
output of module1.py will be
123
72 Does Python support Multithreading? Medium
Yes, Python supports multithreading via the standard library threading module.
However, due to CPython's Global Interpreter Lock (GIL), only one native thread executes Python bytecode at a time.
- I/O-bound tasks (network requests, file operations, database queries): Multithreading provides significant speedups because threads release the GIL during I/O wait.
- CPU-bound tasks (data processing, numerical computations): Multiprocessing via the
multiprocessingmodule orconcurrent.futures.ProcessPoolExecutorshould be used instead to leverage multiple CPU cores.
73 How do I get a list of all files (and directories) in a given directory in Python? Medium
Following is one possible solution there can be other similar ones:
import os
for dirname,dirnames,filenames in os.walk('.'):
#printpathtoallsubdirectoriesfirst.
forsubdirnameindirnames:
printos.path.join(dirname,subdirname)
#printpathtoallfilenames.
forfilenameinfilenames:
printos.path.join(dirname,filename)
#Advancedusage:
#editingthe'dirnames'listwillstopos.walk()from recursing
intothere.
if'.git'indirnames:
#don'tgointoany.gitdirectories.
dirnames.remove('.git')
74 How to append to a string in Python? Medium
Because Python strings are immutable, you cannot directly append characters to an existing string in memory. Each append creates a new string object:
### 1. The += Operator (Small-scale strings):
greeting = "Hello"
greeting += " World" # Creates a new string "Hello World"
### 2. str.join() (Best Practice for Loops & Large Volumes):
Repeatedly appending strings in a loop with += leads to $O(n^2)$ time complexity because memory is repeatedly allocated. The idiomatic high-performance approach is to collect chunks in a list and join them with "".join():
# O(n) linear performance
chunks = []
for i in range(1000):
chunks.append(f"Item-{i}")
result = ", ".join(chunks)
### 3. io.StringIO (Memory-efficient text buffer):
For high-volume text file generation, use io.StringIO which acts as an in-memory file buffer.
75 How to check if string A is substring of string B? Medium
The most readable, pythonic, and performant way to check if substring A exists inside string B is using the in operator:
str_b = "HireXTech Interview Preparation"
str_a = "Interview"
if str_a in str_b:
print(f"'{str_a}' was found!")
### Other String Search Methods:
str.find(sub): Returns the lowest index where the substring starts, or-1if not found:
idx = str_b.find("Tech") # Returns 5
str.index(sub): Likefind(), but raises aValueErrorif the substring does not exist.str.startswith()andstr.endswith(): Checks prefix or suffix matching:
str_b.startswith("HireX") # True
- Regular Expressions (
re.search()): For pattern-based matching.
76 Find all occurrences of a substring in Python? Medium
There is no simple builtin string function that does what you're looking for, but
you could use the more powerful regular expressions:
>>>[m.start()forminre.finditer('test','testtesttesttest')]
[0,5,10,15]//thesearestartingindicesforthestring
77 How do you iterate over a list and pull element indices at the same time? Medium
You are looking for the enumerate function. It takes each element in a sequence
(like a list) and sticks it's location right before it. For example:
>>>my_list=['a','b','c']
>>>list(enumerate(my_list))
[(0,'a'),(1,'b'),(2,'c')]
Note that enumerate() return s an object to be iterated over, so wrapping it in list() just
helps us see what enumerate() produces.
An example that directly answers the question is given below
my_list=['a','b','c']
fori,charinenumerate(my_list):
printi,char
The output is:
0a
1b
2c
78 How does Python's list.sort work at a high level? Is it stable? What's the runtime? Medium
In early pythonversions, the sort function implemented a modified version of
quicksort. However, it was deemed unstable and as of 2.3 they switched to using an
adaptive mergesort algorithm.
79 What does the list comprehension do:? Medium
my_list=[(x,y,z)forxinrange(1,30)foryinrange(x,30)forzin
range(y,30)ifx2+y2==z**2]
It creates a list of tuples called my_list, where the first 2 elements are the
perpendicular sides of right angle triangle and the third value 'z' is the hypotenuse.
[(3,4,5),(5,12,13),(6,8,10),(7,24,25),(8,15,17),(9,12,15),
(10,24,26),(12,16,20),(15,20,25),(20,21,29)]
80 How can we pass optional or keyword parameters from one function to another in Python? Medium
Gather the arguments using the * and ** specifiers in the function's parameter list. This
gives us positional arguments as a tuple and the keyword arguments as a dictionary.
Then we can pass these arguments while calling another function by using * and **:
def fun1(a,*tup,**keywordArg):
…
keywordArg['width']='23.3c'
…
Fun2(a,*tup,**keywordArg)
81 Python How do you make a higher order function in Python? Medium
A higherorder function accepts one or more functions as input and return s a new
function. Sometimes it is required to use function as data To make high order function ,
we need to import functools module The functools.partial() function is used often for
high order function.
82 What is map? Medium
The syntax of map is:
map(aFunction,aSequence)
The first argument is a function to be executed for all the elements of the iterable given
as the second argument. If the function given takes in more than 1 arguments, then
many iterables are given.
83 Are Tuples immutable? Medium
Yes, tuples in Python are immutable. Once created, their elements cannot be changed, added, or removed.
Key implications:
- Hashability: Tuples can be used as dictionary keys or set members if all their elements are hashable.
- Performance: Tuples have less memory overhead and faster creation time compared to lists.
- Safety: Tuples protect data integrity by preventing accidental modifications.
84 Why is not all memory freed when Python exits? Medium
Objects referenced from the global namespaces of Python modules are not
always deallocated when Python exits. This may happen if there are circular
references. There are also certain bits of memory that are allocated by the C library that
are impossible to free (e.g. a tool like the one Purify will complain about these). Python
is, however, aggressive about cleaning up memory on exit and does try to destroy every
single object. If you want to force Python to delete certain things on deallocation, you
can use the at exit module to register one or more exit functions to handle those
deletions.
85 What is Java implementation of Python popularly know? Medium
Jython is the implementation of Python written in Java. It compiles Python source code directly into Java bytecode, allowing Python scripts to seamlessly interact with Java classes and JVM libraries.
86 What is used to create unicode strings in Python? Medium
In Python 3, all strings are Unicode by default (type str).
To create a byte string, prefix the literal with b:
text = 'HireXTech' # Unicode str
raw_bytes = b'HireXTech' # bytes
# Encoding and decoding:
encoded = text.encode('utf-8')
decoded = encoded.decode('utf-8')
87 What is a docstring? Medium
A docstring (documentation string) is a string literal that occurs as the very first statement in a module, class, function, or method definition:
def calculate_compound_interest(principal: float, rate: float, years: int) -> float:
"""Calculates total compound interest on an initial investment.
Args:
principal (float): Initial deposited amount.
rate (float): Annual nominal interest rate as a decimal (e.g. 0.05 for 5%).
years (int): Number of compounding years.
Returns:
float: Total accumulated balance after interest.
"""
return principal * ((1 + rate) ** years)
### Why Docstrings Matter:
- Runtime Accessibility: Docstrings are retained in Python bytecode and accessible via the
.__doc__attribute or thehelp()command. - Automated Documentation: Documentation generators (Sphinx, MkDocs) parse docstrings (following Google, NumPy, or Sphinx styles) into public documentation websites.
- IDE Tooltips: IDEs display docstrings when hovering over functions.
88 Given the list below remove the repetition of an element. Medium
words=['one','one','two','three','three','two']
A bad solution would be to iterate over the list and checking for copies somehow and
then remove them!
A very good solution would be to use the set type. In a Python set, duplicates are not
allowed.
So, list(set(words)) would remove the duplicates.
89 What is wrong with the code? Medium
func([1,2,3])#explicitlypassinginalist
func() #usingadefaultemptylist
def func(n=[]):
#dosomethingwithn
printn
This would result in a NameError. The variable n is local to function func and
can't be accessesd outside. So, printing it won't be possible.
90 What does the below mean? Medium
s = a + '[' + b + ':' + c + ']'
seems like a string is being concatenated. Nothing much can be said without
knowing types of variables a, b, c. Also, if all of the a, b, c are not of type string,
TypeError would be raised. This is because of the string constants ('[' , ']') used in the
statement.
91 Explain the role of repr function. Medium
Python can convert any value to a string by making use of two functions repr() or
str(). The str() function return s representations of values which are humanreadable,
while repr() generates representations which can be read by the interpreter. repr()
return s a machinereadable representation of values, suitable for an exec command.
Following code sniipets shows working of repr() & str() :
def fun():
y=2333.3
x=str(y)
z=repr(y)
print"y:",y
print"str(y):",x
print"repr(y):",z
fun()
————-
output
y:2333.3
str(y):2333.3
repr(y):2333.3000000000002
92 What is LIST comprehensions features of Python used for? Medium
LIST comprehensions features were introduced in Python version 2.0, it creates
a new list based on existing list. It maps a list into another list by applying a function to
each of the elements of the existing list. List comprehensions creates lists without using
map() , filter() or lambda form.
93 Explain how to copy an object in Python.? Medium
There are two ways in which objects can be copied in python. Shallow copy &
Deep copy. Shallow copies duplicate as minute as possible whereas Deep copies
duplicate everything. If a is object to be copied then …
copy.copy(a) return s a shallow copy of a.
copy.deepcopy(a) return s a deep copy of a.
94 Describe how to send mail from a Python script? Medium
The smtplib module def ines an SMTP client session object that can be used to
send mail to any Internet machine.
A sample email is demonstrated below.
import smtplib
SERVER = smtplib.SMTP('smtp.server.domain')
FROM = sender@mail.com
TO = ["user@mail.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Main message
message = """
From: Lincoln < sender@mail.com >
To: CarreerRide user@mail.com
Subject: SMTP email msg
This is a test email. Acknowledge the email by responding.
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
95 Which of the languages does Python resemble in its class syntax? Medium
Python's class syntax resembles C++ and Modula-3, utilizing class definitions, explicit parameter passing (self analogous to this), and multiple inheritance support.
96 Python How to create a multidimensional list? Medium
There are two ways in which Multidimensional list can be created:
By direct initializing the list as shown below to create myList below.
>>>myList=[[227,122,223],[222,321,192],[21,122,444]]
>>>printmyList[0]
>>>printmyList[1][2]
____________________
Output
[227, 122, 223]
192
The second approach is to create a list of the desired length first and then fill in each
element with a newly created lists demonstrated below :
>>>list=[0]*3
>>>foriinrange(3):
>>>list[i]=[0]*2
>>>foriinrange(3):
>>>forjinrange(2):
>>>list[i][j]=i+j
>>>printlist
__________________________
Output
[[0,1],[1,2],[2,3]]
97 Explain the disadvantages of Python? Medium
Disadvantages of Python are: Python isn't the best for memory intensive tasks.
Python is interpreted language & is slow compared to C/C++ or Java.
98 Explain how to make Forms in Python. Medium
As python is scripting language forms processing is done by Python. We need to
import cgi module to access form fields using FieldStorage class.
Every instance of class FieldStorage (for 'form') has the following attributes:
form.name: The name of the field, if specified.
form.filename: If an FTP transaction, the clientside filename.
form.value: The value of the field as a string.
form.file: file object from which data can be read.
form.type: The content type, if applicable.
form.type_options: The options of the 'contenttype' line of the HTTP request, return ed
as a dictionary.
form.disposition: The field 'contentdisposition'; None if unspecified.
form.disposition_options: The options for 'contentdisposition'.
form.headers: All of the HTTP headers return ed as a dictionary.
A code snippet of form handling in python:
import cgi
form=cgi.FieldStorage()
ifnot(form.has_key("name")andform.has_key("age")):
print"<H1>Name&AgenotEntered</H1>"
print"FilltheName&Ageaccurately."
return
print"<p>name:",form["name"].value
print"<p>Age:",form["age"].value
99 Explain how Python is interpreted. Medium
Python program runs directly from the source code. Each type Python programs
are executed code is required. Python converts source code written by the programmer
into intermediate language which is again translated it into the native language
machine language that is executed. So Python is an Interpreted language.
100 Explain how to overload constructors (or methods) in Python.? Medium
In Python, constructors cannot be overloaded by having multiple def __init__ definitions (the last defined one overwrites earlier ones). Instead, constructor overloading is achieved through:
- Default Argument Values:
class User:
def __init__(self, name, email=None):
self.name = name
self.email = email
- **Variable Positional/Keyword Arguments (
*args,kwargs):
class Point:
def __init__(self, *args):
if len(args) == 2:
self.x, self.y = args
elif len(args) == 0:
self.x, self.y = 0, 0
- Alternative Constructors using
@classmethod:
class Date:
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_string(cls, date_str):
year, month, day = map(int, date_str.split('-'))
return cls(year, month, day)
101 What is the difference between List & Tuple in Python.? Medium
LIST vs TUPLES
LIST TUPLES
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can't be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, 'Chelsea', 20] Syntax: tup_1 = (10, 'Chelsea' , 20)
102 What are the key features of Python? Medium
Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
Python is dynamically typed, this means that you don't need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x="I'm a string" without error
Python is well suited to object orientated programming in that it allows the def inition of classes along with composition and inheritance. Python does not have access specifiers (like C++'s public, private).
In Python, functions are first-class objects. This means that they can be assigned to variables, return ed from other functions and passed into functions. Classes are also first class objects
Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it's really quite quick because a lot of the number crunching it does isn't actually done by Python
Python finds use in many spheres – web applications, automation, scientific modeling, big data applications and many more. It's also often used as "glue" code to get other languages and components to play nice.
103 How is Python an interpreted language? Medium
An interpreted language is any programming language which is not in machine level code before runtime. Therefore, Python is an interpreted language.
104 What are Python modules? Name some commonly used built-in modules in Python? Medium
Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.
Some of the commonly used built-in modules are:
os
sys
math
random
data time
JSON
105 What are local variables and global variables in Python? Medium
Global Variables:
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
Local Variables:
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
Example:
a=2
def add():
b=3
c=a+b
print(c)
add()
Output: 5
When you try to access the local variable outside the function add(), it will throw an error.
106 What is type conversion in Python? Medium
Type conversion refers to the conversion of one data type iinto another.
int() – converts any data type into integer type
float() – converts any data type into float type
ord() – converts characters into integer
hex() – converts integers to hexadecimal
oct() – converts integer to octal
tuple() – This function is used to convert to a tuple.
set() – This function return s the type after converting to set.
list() – This function is used to convert any data type to a list type.
dict() – This function is used to convert a tuple of order (key,value) into a dictionary.
str() – Used to convert integer into a string.
complex(real,imag) – This functionconverts real numbers to complex(real,imag) number.
107 How to install Python on Windows and set path variable? Medium
To install Python on Windows, follow the below steps:
Install python from this link: https://www.python.org/downloads/
After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt: cmd python.
Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path.
Look for the path variable, select its value and select 'edit'.
Add a semicolon towards the end of the value if it's not present and then type %PYTHON_HOME%
108 Is indentation required in Python? Medium
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
109 What is the difference between Python Arrays and lists? Medium
Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements whereas lists can hold any data type elements.
Example:
import array as arr
My_Array=arr.array('i',[1,2,3,4])
My_list=[1,'abc',1.20]
print(My_Array)
print(My_list)
Output:
array('i', [1, 2, 3, 4]) [1, 'abc', 1.2]
110 What are functions in Python? Medium
A function is a block of code which is executed only when it is called. To def ine a Python function, the def keyword is used.
Example:
def Newfunc():
print("Hi, Welcome to Edureka")
Newfunc(); #calling the function
Output: Hi, Welcome to Edureka
111 What is __init__? Medium
__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.
Here is an example of how to use it.
class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)
Output:
XYZ
23
20000
112 What is a lambda function in Python and when should you use it? Medium
An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
Example:
1
2
a = lambda x,y : x+y
print(a(5, 6))
Output: 11
113 What is self in Python? Medium
Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it's optional. It helps to differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.
114 How does break, continue and pass work? Medium
Break Allows loop termination when some condition is met and the control is transferred to the next statement.
Continue Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop
Pass Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.
115 What does [::-1} do? Medium
[::-1] is used to reverse the order of an array or a sequence.
For example:
import array as arr
My_Array=arr.array('i',[1,2,3,4,5])
My_Array[::-1]
Output: array('i', [5, 4, 3, 2, 1])
[::-1] reprints a reversed copy of ordered data structures such as an array or a list. the original array or list remains unchanged.
116 How can you randomize the items of a list in place in Python? Medium
Consider the example shown below:
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
The output of the following code is as below.
['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']
117 What Are Python Iterators? Medium
Iterators in Python are array-like objects which allow moving on the next element. We use them in traversing a loop, for example, in a "for" loop.
Python library has a no. of iterators. For example, a list is also an iterator and we can start a for loop over it.
118 How can you generate random numbers in Python? Medium
Random module is the standard module that is used to generate a random number. The method is def ined as:
1
2
import random
random.random
The statement random.random() method return the floating point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are:
randrange(a, b): it chooses an integer and def ine the range in-between [a, b). It return s the elements by selecting it randomly from the range that is specified. It doesn't build a range object.
uniform(a, b): it chooses a floating point number that is def ined in the range of [a,b).Iyt return s the floating point number
normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.
The Random class that is used and instantiated creates an independent multiple random number generators.
119 What is the difference between range & xrange? Medium
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range return s a Python list object and x range return s an xrange object.
This means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you'd like to generate a list for, say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It's a memory hungry beast.
120 What are the generators in Python? Medium
A generator in Python is a special type of iterator that generates values on demand (lazy evaluation) rather than storing the entire dataset in memory at once.
Generators are written like regular functions, but use the yield keyword instead of return:
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
# Values are computed one by one as requested
for num in fibonacci(50):
print(num, end=' ')
# Output: 0 1 1 2 3 5 8 13 21 34
### Why Use Generators:
- Memory Efficiency: Processing a 10GB CSV file line-by-line using a generator requires mere megabytes of RAM, whereas loading it into a list causes an
OutOfMemoryError. - Infinite Streams: Generators can produce infinite sequences (such as real-time sensor streams or UUID sequences).
- Generator Expressions: Inline shorthand syntax
(x**2 for x in range(1000000)).
121 How will you capitalize the first letter of string? Medium
In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it return s the original string.
122 How to comment multiple lines in Python? Medium
Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.
123 What are docstrings in Python? Medium
Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.
Example:
"""
Using docstring as a comment.
This code divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)
Output: 2.0
124 What is the usage of help() and dir() function in Python? Medium
Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
Dir() function: The dir() function is used to display the def ined symbols.
125 Whenever Python exits, why isn't all the memory de-allocated? Medium
Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.
It is impossible to de-allocate those portions of memory that are reserved by the C library.
On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.
126 What is a dictionary in Python? Medium
The built-in datatypes in Python is called dictionary. It def ines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.
Let's take an example:
The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.
1
dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
1
print(dict[Country])
India
1
print(dict[Capital])
Delhi
1
print(dict[PM])
Modi
127 What does this mean: *args, **kwargs? And why would we use it? Medium
We use *args when we aren't sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don't know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.
128 What does len() do? Medium
The built-in len() function returns the number of items (cardinality) in an object:
len("Python") # 6 (number of characters)
len([1, 2, 3, 4, 5]) # 5 (number of elements)
len({'a': 1, 'b': 2}) # 2 (number of keys)
### How len() Works Internally ($O(1)$ Performance):len() calls the object's internal __len__() magic method.
For built-in data types (strings, lists, dicts, tuples), CPython does not iterate over elements to count them. Instead, it reads a cached integer stored directly in the C struct header (PyVarObject.ob_size), executing in instantaneous $O(1)$ constant time.
129 Explain split(), sub(), subn() methods of "re" module in Python. Medium
To modify the strings, Python's "re" module is providing 3 methods. They are:
split() – uses a regex pattern to "split" a given string into a list.
sub() – finds all substrings where the regex pattern matches and then replace them with a different string
subn() – it is similar to sub() and also return s the new string along with the no. of replacements.
130 What are negative indexes and why are they used? Medium
The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses '0' that is uses as first index and '1' as the second index and the process goes on like that.
The index for the negative number starts from '-1' that represents the last index in the sequence and '-2' as the penultimate index and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.
131 What are Python packages? Medium
A Python package is a folder containing modules and typically an __init__.py file. Packages organize modules into a hierarchical dot-separated namespace (e.g., urllib.request), preventing name clashes between modules.
132 How can files be deleted in Python? Medium
To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function.
Example:
1
2
import os
os.remove("xyz.txt")
133 What are the built-in types of Python? Medium
Python provides a comprehensive set of built-in data types organized into distinct structural families:
### 1. Numeric Types:
int: Unlimited-precision integers.float: Double-precision 64-bit IEEE 754 floating-point numbers.complex: Complex numbers with real and imaginary parts (3 + 4j).
### 2. Sequence Types:
str: Unicode character sequences.list: Mutable heterogeneous sequences ([1, 'a', True]).tuple: Immutable sequences ((1, 2, 3)).range: Memory-efficient sequence of numbers.
### 3. Set Types:
set: Mutable collection of unique, hashable items.frozenset: Immutable counterpart ofset.
### 4. Mapping Type:
dict: Key-value hash map ({'id': 101}).
### 5. Binary Types:
bytes,bytearray,memoryview.
### 6. Boolean & None:
bool: Subtype of integer (TrueorFalse).NoneType: The singletonNonerepresenting absence of value.
134 What advantages do NumPy arrays offer over (nested) Python lists? Medium
Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to construct and manipulate.
They have certain limitations: they don't support "vectorized" operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.
135 How to add values to a Python array? Medium
Elements can be added to an array using the append(), extend() and the insert (i,x) functions.
Example:
a=arr.array('d', [1.1 , 2.1 ,3.1] )
a.append(3.4)
print(a)
a.extend([4.5,6.3,6.8])
print(a)
a.insert(2,3.8)
print(a)
Output:
array('d', [1.1, 2.1, 3.1, 3.4])
array('d', [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])
array('d', [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])
136 How to remove values to a Python array? Medium
Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former return s the deleted value whereas the latter does not.
Example:
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
print(a.pop())
print(a.pop(3))
a.remove(1.1)
print(a)
Output:
4.6
3.1
array('d', [2.2, 3.8, 3.7, 1.2])
137 Does Python have OOP concepts? Medium
Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. However, Python can be treated as procedural as well as structural language.
138 What is the difference between deep and shallow copy? Medium
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
Deep copy is used to store the values that are already copied. Deep copy doesn't copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won't affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.
139 How is Multithreading achieved in Python? Medium
Python has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it.
Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn't a good idea.
140 What is the process of compilation and linking in Python? Medium
The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.
The steps that are required in this as:
Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp
Place this file in the Modules/ directory of the distribution which is getting used.
Add a line in the file Setup.local that is present in the Modules/ directory.
Run the file using spam file.o
After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
If the file is changed then run rebuildMakefile by using the command as 'make Makefile'.
141 What are Python libraries? Name a few of them. Medium
Python libraries are a collection of Python packages. Some of the majorly used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.
142 What is split used for? Medium
The split() method is used to separate a given string in Python.
Example:
1
2
a="KausalVikash python"
print(a.split())
Output: ['KausalVikash', 'python']
143 How to import modules in Python? Medium
Modules can be import ed using the import keyword. You can import modules in three ways-
Example:
import array #import ing using the original module name
import array as arr # import ing using an alias name
from array import * #import s everything present in the array module
144 Explain Inheritance in Python with an example. Medium
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.
They are different types of inheritance supported by Python:
Single Inheritance – where a derived class acquires the members of a single super class.
Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
Hierarchical inheritance – from one base class you can inherit any number of child classes
Multiple inheritance – a derived class is inherited from more than one base class.
145 How are classes created in Python? Medium
Class in Python is created using the class keyword.
Example:
class Employee:
def __init__(self, name):
self.name = name
E1=Employee("abc")
print(E1.name)
Output: abc
146 What is monkey patching in Python? Medium
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
Consider the below example:
# m.py
class MyClass:
def f(self):
print("f)()"
We can then run the monkey-patch testing like this:
import m
def monkey_f(self):
print("monkey_f)()"
m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()
The output will be as below:
monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass using the function we def ined, monkey_f(), outside of the module m.
147 Does Python support multiple inheritance? Medium
Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.
148 What is Polymorphism in Python? Medium
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
149 Define encapsulation in Python? Medium
Encapsulation is an Object-Oriented Programming (OOP) principle that binds data (attributes) and the methods operating on that data together into a single cohesive class, while restricting direct outside access to internal implementation details:
### Encapsulation in Python:
Unlike Java or C++, Python does not have strict compile-time private keywords. Instead, it relies on naming conventions and language features:
- Public (No underscore):
self.name(Accessible everywhere). - Protected (Single underscore
_):self._balance(Convention indicating internal use; subclasses and internal methods should use it). - Private (Double underscore
__):self.__pin(Triggers Name Mangling to_ClassName__pinto prevent accidental subclass override).
class BankAccount:
def __init__(self, owner: str, initial_balance: float):
self.owner = owner
self._balance = initial_balance # Encapsulated state
@property
def balance(self) -> float:
return self._balance
def deposit(self, amount: float):
if amount > 0:
self._balance += amount
else:
raise ValueError("Deposit must be positive")
150 How do you do data abstraction in Python? Medium
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
151 Does Python make use of access specifiers? Medium
Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.
152 How to create an empty class in Python? Medium
An empty class is a class that does not have any code def ined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. IN PYTHON THE PASS command does nothing when its executed. it's a null statement.
For example-
class a:
pass
obj=a()
obj.name="xyz"
print("Name = ",obj.name)
Output:
Name = xyz
153 What's The Process To Get The Home Directory Using '~' In Python? Medium
You need to import the os module, and then just a single line would do the rest.
import os
print (os.path.expanduser('~'))
Output:
/home/runner
154 How To Find Bugs Or Perform Static Analysis In A Python Application? Medium
You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding standard.
155 When Is The Python Decorator Used? Medium
Decorators in Python are applied whenever you want to add reusable cross-cutting concerns to functions or classes without duplicating boilerplate code:
### Major Real-World Scenarios:
- API Route Registration:
In web frameworks (FastAPI, Flask), decorators map URL endpoints to handler functions:@app.get('/api/users').
- Authentication & Role Authorization:
Checking if an active session or JWT token exists before executing protected endpoints:@require_auth, @admin_only.
- Caching and Optimization:
Caching expensive database queries or mathematical calculations:@functools.lru_cache(maxsize=256).
- Input Validation & Serialization:
Validating request schemas (e.g. @pydantic.validate_call).
- Logging, Execution Timing & APM Telemetry:
Recording performance metrics, entry/exit logs, and error tracing across service layers.
156 Can Python be used for web client and web server side programming? And which one is best suited to Python? Medium
Python is best suited for web server-side application development due to its vast set of features for creating business logic, database interactions, web server hosting etc.
However, Python can be used as a web client-side application which needs some conversions for a browser to interpret the client side logic. Also, note that Python can be used to create desktop applications which can run as a standalone application such as utilities for test automation.
157 What is the type () in Python? Medium
The built-in method which decides the types of the variable at the program runtime is known as type() in Python. When a single argument is passed through it, then it return s given object type. When 3 arguments pass through this, then it return s a new object type.
158 What are the key points of Python? Medium
Similar to PERL and PHP, Python is processed by the interpreter at runtime. Python supports Object-Oriented style of programming, which encapsulates code within objects.
Derived from other languages, such as ABC, C, C++, Modula-3, SmallTalk, Algol-68, Unix shell, and other scripting languages.
Python is copyrighted, and its source code is available under the GNU General Public License (GPL).
Supports the development of many applications, from text processing to games.
Works for scripting, embedded code and compiled the code.
Detailed
159 What tools can help find bugs or perform the static analysis? Medium
For performing Static Analysis, PyChecker is a tool that detects the bugs in source code and warns the programmer about the style and complexity. Pylint is another tool that authenticates whether the module meets the coding standard.
160 How Does Python Handle Memory Management? Medium
Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can't use it.
And it's the Python memory manager that handles the Private heap. It does the required allocation of the memory for Python objects.
Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.
161 What Are The Principal Differences Between The Lambda And Def? Medium
Lambda Vs. Def.
Def can hold multiple expressions while lambda is a uni-expression function.
Def generates a function and designates a name to call it later. Lambda forms a function object and return s it.
Def can have a return statement. Lambda can't have return statements.
Lambda supports to get used inside a list and dictionary.
162 Write A Reg Expression That Confirms An Email Id Using The Python Reg Expression Module "Re"? Medium
Python has a regular expression module "re."
Check out the "re" expression that can check the email id for .com and .co.in subdomain.
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
163 What is the output of slicing an index beyond list length in Python, and does it raise an error? Medium
list = ['a', 'b', 'c', 'd', 'e']
print (list[10:])
The result of the above lines of code is []. There won't be any error like an IndexError.
You should know that trying to fetch a member from the list using an index that exceeds the member count (for example, attempting to access list[10] as given in the question) would yield an IndexError. By the way, retrieving only a slice at the starting index that surpasses the no. of items in the list won't result in an IndexError. It will just return an empty list.
164 Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason For The Same? Medium
Historically, Python had no switch statement for over 30 years because Guido van Rossum and the Python core team felt that if-elif-else chains and dictionary dispatch tables were sufficient and pythonic.
### Modern Update: Python 3.10+ Added match/case
Starting in Python 3.10 (October 2021), Python introduced Structural Pattern Matching via the match and case keywords (PEP 634):
def process_command(command):
match command.split():
case ["quit"]:
return "Exiting"
case ["go", direction]:
return f"Heading {direction}"
case ["save", filename]:
return f"Saving to {filename}"
case _:
return "Command not recognized"
Unlike standard switch statements in C/Java which only match primitive values, Python's match/case performs deep structural pattern matching against sequences, mappings, types, and object attributes.
165 What Is A Built-In Function That Python Uses To Iterate Over A Number Sequence? Medium
Range() generates a list of numbers, which is used to iterate over for loops.
for i in range(5):
print(i)
The range() function accompanies two sets of parameters.
range(stop)
stop: It is the no. of integers to generate and starts from zero. eg. range(3) == [0, 1, 2].
range([start], stop[, step])
Start: It is the starting no. of the sequence.
Stop: It specifies the upper limit of the sequence.
Step: It is the incrementing factor for generating the sequence.
Points to note:
Only integer arguments are allowed.
Parameters can be positive or negative.
The range() function in Python starts from the zeroth index.
166 What Are The Optional Statements Possible Inside A Try-Except Block In Python? Medium
There are two optional clauses you can use in the try-except block.
The "else" clause
It is useful if you want to run a piece of code when the try block doesn't create an exception.
The "finally" clause
It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.
167 What Is A String In Python? Medium
A string in Python is a sequence of alpha-numeric characters. They are immutable objects. It means that they don't allow modification once they get assigned a value. Python provides several methods, such as join(), replace(), or split() to alter strings. But none of these change the original object.
168 What Is Slicing In Python? Medium
Slicing is a string operation for extracting a part of the string, or some part of a list. In Python, a string (say text) begins at index 0, and the nth character stores at position text[n-1]. Python can also perform reverse indexing, i.e., in the backward direction, with the help of negative numbers. In Python, the slice() is also a constructor function which generates a slice object. The result is a set of indices mentioned by range(start, stop, step). The slice() method allows three parameters. 1. start – starting number for the slicing to begin. 2. stop – the number which indicates the end of slicing. 3. step – the value to increment after each index (def ault = 1).
169 What Is %S In Python? Medium
Python has support for formatting any value into a string. It may contain quite complex expressions.
One of the common usages is to push values into a string with the %s format specifier. The formatting operation in Python has the comparable syntax as the C function printf() has.
170 What Is The Index In Python? Medium
An index is an integer data type which denotes a position within an ordered list or a string.
In Python, strings are also lists of characters. We can access them using the index which begins from zero and goes to the length minus one.
For example, in the string "Program," the indexing happens like this:
Program 0 1 2 3 4 5
171 What Is A Function In Python Programming? Medium
A function is an object which represents a block of code and is a reusable entity. It brings modularity to a program and a higher degree of code reusability.
Python has given us many built-in functions such as print() and provides the ability to create user-def ined functions.
172 How Many Basic Types Of Functions Are Available In Python? Medium
Python gives us two basic types of functions.
- Built-in, and
- User-def ined.
The built-in functions happen to be part of the Python language. Some of these are print(), dir(), len(), and abs() etc.
173 How Do We Write A Function In Python? Medium
We can create a Python function in the following manner.
Step-1: to begin the function, start writing with the keyword def and then mention the function name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A colon, in the end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for execution.
174 What Is A Function Call Or A Callable Object In Python? Medium
A function in Python gets treated as a callable object. It can allow some arguments and also return a value or multiple values in the form of a tuple. Apart from the function, Python has other constructs, such as classes or the class instances which fits in the same category.
175 What Is The Return Keyword Used For In Python? Medium
The purpose of a function is to receive the inputs and return some output.
The return is a Python statement which we can use in a function for sending a value back to its caller.
176 What Is "Call By Value" In Python? Medium
In call-by-value, the argument whether an expression or a value gets bound to the respective variable in the function.
Python will treat that variable as local in the function-level scope. Any changes made to that variable will remain local and will not reflect outside the function.
177 What Is "Call By Reference" In Python? Medium
We use both "call-by-reference" and "pass-by-reference" interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller.
This scheme also has the advantage of bringing more time and space efficiency because it leaves the need for creating local copies.
On the contrary, the disadvantage could be that a variable can get changed accidentally during a function call. Hence, the programmers need to handle in the code to avoid such uncertainty.
178 What Is The Return Value Of The Trunc() Function? Medium
The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.
179 Is It Mandatory For A Python Function To Return A Value? Medium
No, it is not mandatory for a Python function to explicitly return a value using the return keyword.
### Implicit Return Behavior:
If a function finishes executing without encountering a return statement (or reaches an empty return), Python automatically returns None:
def log_message(msg):
print(f"[LOG]: {msg}")
result = log_message("System starting")
print(result) # Output: None
print(result is None) # Output: True
In type hints, functions that perform actions without returning data are typed with -> None:
def cleanup_temp_files() -> None:
pass
180 What Does The Continue Do In Python? Medium
The continue is a jump statement in Python which moves the control to execute the next iteration in a loop leaving all the remaining instructions in the block unexecuted.
The continue statement is applicable for both the "while" and "for" loops.
181 What Is The Purpose Of Id() Function In Python? Medium
The id() is one of the built-in functions in Python.
Signature: id(object)
It accepts one parameter and return s a unique identifier associated with the input object.
182 What Does The *Args Do In Python? Medium
We use *args as a parameter in the function header. It gives us the ability to pass N (variable) number of arguments.
Please note that this type of argument syntax doesn't allow passing a named argument to the function.
Example of using the *args:
# Python code to demonstrate
# *args for dynamic arguments
def fn(*argList):
for argx in argList:
print (argx)
fn('I', 'am', 'Learning', 'Python')
The output:
I
am
Learning
Python
183 Does Python Have A Main() Method? Medium
The main() is the entry point function which happens to be called first in most programming languages.
Since Python is interpreter-based, so it sequentially executes the lines of the code one-by-one.
Python also does have a Main() method. But it gets executed whenever we run our Python script either by directly clicking it or starts it from the command line.
We can also override the Python def ault main() function using the Python if statement. Please see the below code.
print("Welcome")
print("__name__ contains: ", __name__)
def main():
print("Testing the main function")
if __name__ == '__main__':
main()
The output:
Welcome
__name__ contains: __main__
Testing the main function
184 What Does The __ Name __ Do In Python? Medium
The __name__ is a unique variable. Since Python doesn't expose the main() function, so when its interpreter gets to run the script, it first executes the code which is at level 0 indentation.
To see whether the main() gets called, we can use the __name__ variable in an if clause compares with the value "__main__."
185 What Is The Purpose Of "End" In Python? Medium
Python's print() function always prints a newline in the end. The print() function accepts an optional parameter known as the 'end.' Its value is '\n' by def ault. We can change the end character in a print(statement with the value of our choice using this parameter.)
# Example: Print a instead of the new line in the end.
print("Let's learn" , end = ' ')
print("Python")
# Printing a dot in the end.
print("Learn to code from techbeamers" , end = '.')
print("com", end = ' ')
The output is:
Let's learn Python
Learn to code from techbeamers.com
186 When Should You Use The "Break" In Python? Medium
Python provides a break statement to exit from a loop. Whenever the break hits in the code, the control of the program immediately exits from the body of the loop.
The break statement in a nested loop causes the control to exit from the inner iterative block.
187 What Is The Difference Between Pass And Continue In Python? Medium
The continue statement makes the loop to resume from the next iteration.
On the contrary, the pass statement instructs to do nothing, and the remainder of the code executes as usual.
188 What Does The Len() Function Do In Python? Medium
In Python, the len() is a primary string function. It determines the length of an input string.
>>> some_string = 'techbeamers'
>>> len(some_string)
11
189 What Does The Chr() Function Do In Python? Medium
The chr() function got re-added in Python 3.2. In version 3.0, it got removed.
It return s the string denoting a character whose Unicode code point is an integer.
For example, the chr(122) return s the string 'z' whereas the chr(1212) return s the string 'Ҽ'.
190 What Does The Ord() Function Do In Python? Medium
The ord(char) in Python takes a string of size one and return s an integer denoting the Unicode code format of the character in case of a Unicode type object, or the value of the byte if the argument is of 8-bit string type.
>>> ord("z")
122
191 What Is Rstrip() In Python? Medium
Python provides the rstrip() method which duplicates the string but leaves out the whitespace characters from the end.
The rstrip() escapes the characters from the right end based on the argument value, i.e., a string mentioning the group of characters to get excluded.
The signature of the rstrip() is:
str.rstrip([char sequence/pre>
#Example
test_str = 'Programming '
# The trailing whitespaces are excluded
print(test_str.rstrip())
192 What Is Whitespace In Python? Medium
Whitespace represents the characters that we use for spacing and separation.
They possess an "empty" representation. In Python, it could be a tab or space.
193 What Is Isalpha() In Python? Medium
Python provides this built-in isalpha() function for the string handling purpose.
It return s True if all characters in the string are of alphabet type, else it return s False.
194 How Do You Use The Split() Function In Python? Medium
Python's split() function works on strings to cut a large piece into smaller chunks, or sub-strings. We can specify a separator to start splitting, or it uses the space as one by def ault.
#Example
str = 'pdf csv json'
print(str.split(" "))
print(str.split())
The output:
['pdf', 'csv', 'json']
['pdf', 'csv', 'json']
195 What Does The Join Method Do In Python? Medium
The str.join() method concatenates the elements of an iterable (such as a list or tuple of strings) into a single unified string, separated by the calling string:
tags = ['react', 'nextjs', 'typescript']
slug = "-".join(tags)
print(slug) # Output: "react-nextjs-typescript"
words = ['Hello', 'World']
sentence = " ".join(words)
print(sentence) # Output: "Hello World"
### Crucial Architectural Advantage:str.join() is significantly faster than using the += operator inside a loop. join() pre-calculates the exact total memory size required for the output string and performs a single memory allocation, operating in linear $O(n)$ time.
196 What Does The Title() Method Do In Python? Medium
Python provides the title() method to convert the first letter in each word to capital format while the rest turns to Lowercase.
#Example
str = 'lEaRn pYtHoN'
print(str.title())
The output:
Learn Python
Now, check out some general purpose Python interview questions.
197 What Makes The CPython Different From Python? Medium
CPython has its core developed in C. The prefix 'C' represents this fact. It runs an interpreter loop used for translating the Python-ish code to C language.
198 How Is Python Thread Safe? Medium
Python ensures safe access to threads. It uses the GIL mutex to set synchronization. If a thread loses the GIL lock at any time, then you have to make the code thread-safe.
For example, many of the Python operations execute as atomic such as calling the sort() method on a list.
199 How Does Python Manage The Memory? Medium
Python implements a heap manager internally which holds all of its objects and data structures.
This heap manager does the allocation/de-allocation of heap space for objects.
200 What Is The Set Object In Python? Medium
Sets are unordered collection objects in Python. They store unique and immutable objects. Python has its implementation derived from mathematics.
201 What Is The Use Of The Dictionary In Python? Medium
A dictionary has a group of objects (the keys) map to another group of objects (the values). A Python dictionary represents a mapping of unique Keys to Values.
They are mutable and hence will not change. The values associated with the keys can be of any Python types.
202 Is Python List A Linked List? Medium
A Python list is a variable-length array which is different from C-style linked lists.
Internally, it has a contiguous array for referencing to other objects and stores a pointer to the array variable and its length in the list head structure.
Here are some Python interview questions on classes and objects
203 What Is Class In Python? Medium
Python supports object-oriented programming and provides almost all OOP features to use in programs.
A Python class is a blueprint for creating the objects. It def ines member variables and gets their behavior associated with them.
We can make it by using the keyword "class." An object gets created from the constructor. This object represents the instance of the class.
In Python, we generate classes and instances in the following way.
>>>class Human: # Create the class
... pass
>>>man = Human() # Create the instance
>>>print(man)
<__main__.Human object at 0x0000000003559E10>
204 What Are Attributes And Methods In A Python Class? Medium
A class is useless if it has not def ined any functionality. We can do so by adding attributes. They work as containers for data and functions. We can add an attribute directly specifying inside the class body.
>>> class Human:
... profession = "programmer" # specify the attribute 'profession' of the class
>>> man = Human()
>>> print(man.profession)
programmer
After we added the attributes, we can go on to def ine the functions. Generally, we call them methods. In the method signature, we always have to provide the first argument with a self-keyword.
>>> class Human:
profession = "programmer"
def set_profession(self, new_profession):
self.profession = new_profession
>>> man = Human()
>>> man.set_profession("Manager")
>>> print(man.profession)
Manager
205 How To Assign Values For The Class Attributes At Runtime? Medium
We can specify the values for the attributes at runtime. We need to add an init method and pass input to object constructor. See the following example demonstrating this.
>>> class Human:
def __init__(self, profession):
self.profession = profession
def set_profession(self, new_profession):
self.profession = new_profession
>>> man = Human("Manager")
>>> print(man.profession)
Manager
206 What Is Inheritance In Python Programming? Medium
Inheritance is an OOP mechanism which allows an object to access its parent class features. It carries forward the base class functionality to the child.
Python Interview Questions - Inheritance
We do it intentionally to abstract away the similar code in different classes.
The common code rests with the base class, and the child class objects can access it via inheritance. Check out the below example.
class PC: # Base class
processor = "Xeon" # Common attribute
def set_processor(self, new_processor):
processor = new_processor
class Desktop(PC): # Derived class
os = "Mac OS High Sierra" # Personalized attribute
ram = "32 GB"
class Laptop(PC): # Derived class
os = "Windows 10 Pro 64" # Personalized attribute
ram = "16 GB"
desk = Desktop()
print(desk.processor, desk.os, desk.ram)
lap = Laptop()
print(lap.processor, lap.os, lap.ram)
The output:
Xeon Mac OS High Sierra 32 GB
Xeon Windows 10 Pro 64 16 GB
207 What Is Composition In Python? Medium
The composition is also a type of inheritance in Python. It intends to inherit from the base class but a little differently, i.e., by using an instance variable of the base class acting as a member of the derived class.
See the below diagram.
Python Interview Questions - Composition
To demonstrate composition, we need to instantiate other objects in the class and then make use of those instances.
class PC: # Base class
processor = "Xeon" # Common attribute
def __init__(self, processor, ram):
self.processor = processor
self.ram = ram
def set_processor(self, new_processor):
processor = new_processor
def get_PC(self):
return "%s cpu & %s ram" % (self.processor, self.ram)
class Tablet():
make = "Intel"
def __init__(self, processor, ram, make):
self.PC = PC(processor, ram) # Composition
self.make = make
def get_Tablet(self):
return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram, self.make)
if __name__ == "__main__":
tab = Tablet("i7", "16 GB", "Intel")
print(tab.get_Tablet())
The output is:
Tablet with i7 CPU & 16 GB ram by Intel
208 What Are Errors And Exceptions In Python Programs? Medium
Errors are coding issues in a program which may cause it to exit abnormally.
On the contrary, exceptions happen due to the occurrence of an external event which interrupts the normal flow of the program.
209 How Do You Handle Exceptions With Try/Except/Finally In Python? Medium
Python lay down Try, Except, Finally constructs to handle errors as well as Exceptions. We enclose the unsafe code indented under the try block. And we can keep our fall-back code inside the except block. Any instructions intended for execution last should come under the finally block.
try:
print("Executing code in the try block")
print(exception)
except:
print("Entering in the except block")
finally:
print("Reached to the final block")
The output is:
Executing code in the try block
Entering in the except block
Reached to the final block
210 How Do You Raise Exceptions For A Predefined Condition In Python? Medium
We can raise an exception based on some condition.
For example, if we want the user to enter only odd numbers, else will raise an exception.
# Example - Raise an exception
while True:
try:
value = int(input("Enter an odd number- "))
if value%2 == 0:
raise ValueError("Exited due to invalid input!!!")
else:
print("Value entered is : %s" % value)
except ValueError as ex:
print(ex)
break
The output is:
Enter an odd number- 2
Exited due to invalid input!!!
Enter an odd number- 1
Value entered is : 1
Enter an odd number-
211 What Is The Difference Between An Iterator And Iterable? Medium
The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are also iterable containers which return an iterator while traversing.
Here are some advanced-level Python interview questions.
212 What Are Python Generators? Medium
A Generator is a kind of function which lets us specify a function that acts like an iterator and hence can get used in a "for" loop.
In a generator function, the yield keyword substitutes the return statement.
# Simple Python function
def fn():
return "Simple Python function."
# Python Generator function
def generate():
yield "Python Generator function."
print(next(generate()))
The output is:
Python Generator function.
213 What Are Closures In Python? Medium
Python closures are function objects return ed by another function. We use them to eliminate code redundancy.
In the example below, we've written a simple closure for multiplying numbers.
def multiply_number(num):
def product(number):
'product() here is a closure'
return num * number
return product
num_2 = multiply_number(2)
print(num_2(11))
print(num_2(24))
num_6 = multiply_number(6)
print(num_6(1))
The output is:
22
48
6
214 What Are Decorators In Python? Medium
Python decorator gives us the ability to add new behavior to the given objects dynamically. In the example below, we've written a simple example to display a message pre and post the execution of a function.
def decorator_sample(func):
def decorator_hook(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return decorator_hook
@decorator_sample
def product(x, y):
"Function to multiply two numbers."
return x * y
print(product(3, 3))
The output is:
Before the function call
After the function call
9
215 How Do You Create A Dictionary In Python? Medium
Let's take the example of building site statistics. For this, we first need to break up the key-value pairs using a colon(":"). The keys should be of an immutable type, i.e., so we'll use the data-types which don't allow changes at runtime. We'll choose from an int, string, or tuple.
However, we can take values of any kind. For distinguishing the data pairs, we can use a comma(",") and keep the whole stuff inside curly braces({…}).
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> type(site_stats)
<class 'dict'>
>>> print(site_stats)
{'type': 'organic', 'site': 'tecbeamers.com', 'traffic': 10000}
216 How Do You Read From A Dictionary In Python? Medium
To fetch data from a dictionary, we can directly access using the keys. We can enclose a "key" using brackets […] after mentioning the variable name corresponding to the dictionary.
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats["traffic"])
We can even call the get method to fetch the values from a dict. It also let us set a def ault value. If the key is missing, then the KeyError would occur.
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats.get('site'))
tecbeamers.com
217 How Do You Traverse Through A Dictionary Object In Python? Medium
We can use the "for" and "in" loop for traversing the dictionary object.
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> for k, v in site_stats.items():
print("The key is: %s" % k)
print("The value is: %s" % v)
print("++++++++++++++++++++++++")
The output is:
The key is: type
The value is: organic
++++++++++++++++++++++++
The key is: site
The value is: tecbeamers.com
++++++++++++++++++++++++
The key is: traffic
The value is: 10000
++++++++++++++++++++++++
218 How Do You Add Elements To A Dictionary In Python? Medium
We can add elements by modifying the dictionary with a fresh key and then set the value to it.
>>> # Setup a blank dictionary
>>> site_stats = {}
>>> site_stats['site'] = 'google.com'
>>> site_stats['traffic'] = 10000000000
>>> site_stats['type'] = 'Referral'
>>> print(site_stats)
{'type': 'Referral', 'site': 'google.com', 'traffic': 10000000000}
We can even join two dictionaries to get a bigger dictionary with the help of the update() method.
>>> site_stats['site'] = 'google.co.in'
>>> print(site_stats)
{'site': 'google.co.in'}
>>> site_stats_new = {'traffic': 1000000, "type": "social media"}
>>> site_stats.update(site_stats_new)
>>> print(site_stats)
{'type': 'social media', 'site': 'google.co.in', 'traffic': 1000000}
219 How Do You Delete Elements Of A Dictionary In Python? Medium
We can delete a key in a dictionary by using the del() method.
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> del site_stats["type"]
>>> print(site_stats)
{'site': 'google.co.in', 'traffic': 1000000}
Another method, we can use is the pop() function. It accepts the key as the parameter. Also, a second parameter, we can pass a def ault value if the key doesn't exist.
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> print(site_stats.pop("type", None))
organic
>>> print(site_stats)
{'site': 'tecbeamers.com', 'traffic': 10000}
220 How Do You Check The Presence Of A Key In A Dictionary? Medium
We can use Python's "in" operator to test the presence of a key inside a dict object.
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"}
>>> 'site' in site_stats
True
>>> 'traffic' in site_stats
True
>>> "type" in site_stats
True
Earlier, Python also provided the has_key() method which got deprecated.
221 What Is The Syntax For List Comprehension In Python? Medium
The signature for the list comprehension is as follows:
[ expression(var) for var in iterable ]
For example, the below code will return all the numbers from 10 to 20 and store them in a list.
>>> alist = [var for var in range(10, 20)]
>>> print(alist)
222 What Is The Syntax For Dictionary Comprehension In Python? Medium
A dictionary has the same syntax as was for the list comprehension but the difference is that it uses curly braces:
{ aKey, itsValue for aKey in iterable }
For example, the below code will return all the numbers 10 to 20 as the keys and will store the respective squares of those numbers as the values.
>>> adict = {var:var**2 for var in range(10, 20)}
>>> print(adict)
223 What Is The Syntax For Generator Expression In Python? Medium
The syntax for generator expression matches with the list comprehension, but the difference is that it uses parenthesis:
( expression(var) for var in iterable )
For example, the below code will create a generator object that generates the values from 10 to 20 upon using it.
>>> (var for var in range(10, 20))
at 0x0000000003668728>
>>> list((var for var in range(10, 20)))
Now, see more Python interview questions for practice.
224 How Do You Write A Conditional Expression In Python? Medium
We can utilize the following single statement as a conditional expression. def ault_statment if Condition else another_statement
>>> no_of_days = 366
>>> is_leap_year = "Yes" if no_of_days == 366 else "No"
>>> print(is_leap_year)
Yes
225 What Do You Know About The Python Enumerate? Medium
While using the iterators, sometimes we might have a use case to store the count of iterations. Python gets this task quite easy for us by giving a built-in method known as the enumerate().
The enumerate() function attaches a counter variable to an iterable and return s it as the "enumerated" object.
We can use this object directly in the "for" loops or transform it into a list of tuples by calling the list() method. It has the following signature:
enumerate(iterable, to_begin=0)
Arguments:
iterable: array type object which enables iteration
to_begin: the base index for the counter is to get started, its def ault value is 0
# Example - enumerate function
alist = ["apple","mango", "orange"]
astr = "banana"
# Let's set the enumerate objects
list_obj = enumerate(alist)
str_obj = enumerate(astr)
print("list_obj type:", type(list_obj))
print("str_obj type:", type(str_obj))
print(list(enumerate(alist)) )
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))
The output is:
list_obj type: <class 'enumerate'>
str_obj type: <class 'enumerate'>
[(0, 'apple'), (1, 'mango'), (2, 'orange')]
[(2, 'b'), (3, 'a'), (4, 'n'), (5, 'a'), (6, 'n'), (7, 'a')]
226 What Is The Use Of Globals() Function In Python? Medium
The globals() function in Python return s the current global symbol table as a dictionary object.
Python maintains a symbol table to keep all necessary information about a program. This info includes the names of variables, methods, and classes used by the program.
All the information in this table remains in the global scope of the program and Python allows us to retrieve it using the globals() method.
Signature: globals()
Arguments: None
# Example: globals() function
x = 9
def fn():
y = 3
z = y + x
# Calling the globals() method
z = globals()['x'] = z
return z
# Test Code
ret = fn()
print(ret)
The output is:
12
227 Why Do You Use The Zip() Method In Python? Medium
The zip method lets us map the corresponding index of multiple containers so that we can use them using as a single unit.
Signature:
zip(*iterators)
Arguments:
Python iterables or collections (e.g., list, string, etc.)
Returns:
A single iterator object with combined mapped values
# Example: zip() function
emp = [ "tom", "john", "jerry", "jake" ]
age = [ 32, 28, 33, 44 ]
dept = [ 'HR', 'Accounts', 'R&D', 'IT' ]
# call zip() to map values
out = zip(emp, age, dept)
# convert all values for printing them as set
out = set(out)
# Displaying the final values
print ("The output of zip() is : ",end="")
print (out)
The output is:
The output of zip() is : {('jerry', 33, 'R&D'), ('jake', 44, 'IT'), ('john', 28, 'Accounts'), ('tom', 32, 'HR')}
228 What Are Class Or Static Variables In Python Programming? Medium
In Python, all the objects share common class or static variables.
But the instance or non-static variables are altogether different for different objects.
The programming languages like C++ and Java need to use the static keyword to make a variable as the class variable. However, Python has a unique way to declare a static variable.
All names initialized with a value in the class declaration becomes the class variables. And those which get assigned values in the class methods becomes the instance variables.
# Example
class Test:
aclass = 'programming' # A class variable
def __init__(self, ainst):
self.ainst = ainst # An instance variable
# Objects of CSStudent class
test1 = Test(1)
test2 = Test(2)
print(test1.aclass)
print(test2.aclass)
print(test1.ainst)
print(test2.ainst)
# A class variable is also accessible using the class name
print(Test.aclass)
The output is:
programming
programming
1
2
programming
Let's now answer some advanced-level Python interview questions.
229 How Does The Ternary Operator Work In Python? Medium
The ternary operator is an alternative for the conditional statements. It combines true or false values with a statement that you need to test.
The syntax would look like the one given below.
[onTrue] if [Condition] else [onFalse]
x, y = 35, 75
smaller = x if x < y else y
print(smaller)
230 What Does The "Self" Keyword Do? Medium
The self is a Python keyword which represents a variable that holds the instance of an object.
In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.
231 What Are The Different Methods To Copy An Object In Python? Medium
There are two ways to copy objects in Python.
copy.copy() function
It makes a copy of the file from source to destination.
It'll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It'll return a deep copy of the parameter that you can pass to the function.
257: What Is The Purpose Of Docstrings In Python?
In Python, the docstring is what we call as the docstrings. It sets a process of recording Python functions, modules, and classes.
232 Which Python Function Will You Use To Convert A Number To A String? Medium
For converting a number into a string, you can use the built-in function str(). If you want an octal or hexadecimal representation, use the inbuilt function oct() or hex().
233 How Do You Debug A Program In Python? Is It Possible To Step Through The Python Code? Medium
Yes, we can use the Python debugger (pdb) to debug any Python program. And if we start a program using pdb, then it let us even step through the code.
234 List Down Some Of The PDB Commands For Debugging Python Programs? Medium
Here are a few PDB commands to start debugging Python code.
Add breakpoint (b)
Resume execution (c)
Step by step debugging (s)
Move to the next line (n)
List source code (l)
Print an expression (p)
235 What Is The Command To Debug A Python Program? Medium
Python provides several tools to interactively debug programs from the command line:
### 1. The Built-in breakpoint() Function (Python 3.7+ - Recommended):
Insert breakpoint() directly into your code where you want execution to pause:
def calculate_metrics(data):
total = sum(data)
breakpoint() # Drops into interactive debugger here
return total / len(data)
### 2. Invoking pdb from the Terminal:
Launch any script under the Python debugger directly from your terminal:
python3 -m pdb script.py
### Essential PDB Debugging Commands:
n(next): Step to the next line of code.s(step): Step into the function call.c(continue): Continue execution until the next breakpoint.p variable(print): Print current value ofvariable.q(quit): Exit the debugger.
236 How Do You Monitor The Code Flow Of A Program In Python? Medium
In Python, we can use the sys module's settrace() method to setup trace hooks and monitor the functions inside a program.
You need to def ine a trace callback method and pass it to the settrace() function. The callback should specify three arguments as shown below.
import sys
def trace_calls(frame, event, arg):
# The 'call' event occurs before a function gets executed.
if event != 'call':
return
# Next, inspect the frame data and print(information.)
print('Function name=%s, line num=%s' % )(frame.f_code.co_name, frame.f_lineno)
return
def demo2():
print('in demo2)()'
def demo1():
print('in demo1)()'
demo2()
sys.settrace(trace_calls)
demo1()
237 How long can an identifier be in Python? Medium
According to the official Python documentation, an identifier can be of any length. However, PEP 8 suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says 'readability counts'. So, a very long identifier will violate PEP-8 and PEP-20.
Apart from that, there are certain rules we must follow to name one:
According to the official Python documentation, an identifier can be of any length. However, PEP 8 suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says 'readability counts'. So, a very long identifier will violate PEP-8 and PEP-20.
Apart from that, there are certain rules we must follow to name one:
It can only begin with an underscore or a character from A-Z or a-z.
The rest of it can contain anything from the following: A-Z/a-z/_/0-9.
Python is case-sensitive, as we discussed in the previous question.
Keywords cannot be used as identifiers. Python has the following keywords:
and def False import not True
as del finally in or try
assert elif for is pass while
break else from lambda print(with)
class except global None raise yield
continue exec if nonlocal return
238 How would you convert a string into lowercase? Medium
We use the lower() method for this.
>>> 'AyuShi'.lower()
'ayushi'
To convert it into uppercase, then, we use upper().
>>> 'AyuShi'.upper()
'AYUSHI'
Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and islower().
>>> 'AyuShi'.isupper()
False
>>> 'AYUSHI'.isupper()
True
>>> 'ayushi'.islower()
True
>>> '@yu$hi'.islower()
True
>>> '@YU$HI'.isupper()
True
So, characters like @ and $ will suffice for both cases
Also, istitle() will tell us if a string is in title case.
>>> 'The Corpse Bride'.istitle()
True
239 Explain help() and dir() functions in Python? Medium
The help() function displays the documentation string and help for its argument.
>>> import copy
>>> help(copy.copy)
Help on function copy in module copy:
copy(x)
Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
The dir() function displays all the members of an object(any kind).
>>> dir(copy.copy)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
240 How do you get a list of all the keys in a dictionary? Medium
In Python, you retrieve dictionary keys using the .keys() method or by converting the dictionary directly to a list:
user = {'id': 101, 'username': 'alex', 'role': 'admin'}
# 1. Direct conversion to list (Recommended)
key_list = list(user)
print(key_list) # ['id', 'username', 'role']
# 2. Using .keys()
dict_keys_view = user.keys() # Returns a dynamic dict_keys view object
keys_as_list = list(user.keys())
### Key Detail: Dictionary Viewsuser.keys() returns a dynamic view object. If the dictionary changes, the view immediately reflects those changes without allocating a new list in memory.
241 How will you check if all characters in a string are alphanumeric? Medium
Use the .isalnum() method on a string. It returns True if all characters in the string are alphanumeric (letters or numbers) and there is at least one character:
print('Python3'.isalnum()) # True
print('Python 3'.isalnum()) # False (space is not alphanumeric)
242 With Python, how do you find out which directory you are currently in? Medium
To find this, we use the function/method getcwd(). We import it from the module os.
>>> import os
>>> os.getcwd()
'C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32'
>>> type(os.getcwd)
<class 'builtin_function_or_method'>
We can also change the current working directory with chdir().
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.getcwd()
'C:\\Users\\lifei\\Desktop'
243 How do you insert an object at a given index in Python? Medium
Let's build a list first.
>>> a=[1,2,4]
Now, we use the method insert. The first argument is the index at which to insert, the second is the value to insert.
>>> a.insert(2,3)
>>> a
[1, 2, 3, 4]
244 How do you reverse a list? Medium
Using the reverse() method.
>>> a.reverse()
>>> a
[4, 3, 2, 1]
You can also do it via slicing from right to left:
>>> a[::-1]
>>> a
[1, 2, 3, 4]
This gives us the original list because we already reversed it once. However, this does not modify the original list to reverse it.
245 How does a function return values? Medium
A Python function returns values to its caller using the return statement:
### Return Behaviors:
- Single Value:
def square(n):
return n * n
- Multiple Values (Unpacked as a Tuple):
Python functions can return multiple comma-separated values, which Python automatically packs into an immutable tuple:
def get_coordinates():
return 37.7749, -122.4194 # Returns tuple (37.7749, -122.4194)
lat, lng = get_coordinates() # Tuple unpacking
- Early Exit:
returnimmediately terminates function execution, bypassing subsequent lines.
246 How would you define a block in Python? Medium
For any kind of statements, we possibly need to def ine a block of code under them. However, Python does not support curly braces. This means we must end such statements with colons and then indent the blocks under those with the same amount.
>>> if 3>1:
print("Hello")
print("Goodbye")
Hello
Goodbye
247 Will the do-while loop work if you don't end it with a semicolon? Medium
Trick question! Python does not support an intrinsic do-while loop. Secondly, to terminate do-while loops is a necessity for languages like C++.
248 In one line, show us how you'll get the max alphabetical character from a string.? Medium
For this, we'll simply use the max function.
>>> max('flyiNg')
'y'
The following are the ASCII values for all the letters of this string-
f- 102
l- 108
y- 121
i- 105
N- 78
g- 103
By this logic, try to explain the following line of code-
>>> max('fly{}iNg')
'}'
(Bonus: } – 125)
249 Can you name ten built-in functions in Python and explain each in brief? Medium
Ten Built-in Functions, you say? Okay, here you go.
complex()- Creates a complex number.
>>> complex(3.5,4)
(3.5+4j)
eval()- Parses a string as an expression.
>>> eval('print(max(22,22.0)-min(2,3))')
20
filter()- Filters in items for which the condition is true.
>>> list(filter(lambda x:x%2==0,[1,2,0,False]))
[2, 0, False]
format()- Lets us format a string.
>>> print("a={0} but b={1}".format(a,b))
a=2 but b=3
hash()- Returns the hash value of an object.
>>> hash(3.7)
644245917
hex()- Converts an integer to a hexadecimal.
>>> hex(14)
'0xe'
input()- Reads and return s a line of string.
>>> input('Enter a number')
Enter a number7
'7'
len()- Returns the length of an object.
>>> len('Ayushi')
6
locals()- Returns a dictionary of the current local symbol table.
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 2, 'b': 3}
open()- Opens a file.
>>> file=open('tabs.txt')
250 How will you convert a list into a string? Medium
We will use the join() method for this.
>>> nums=['one','two','three','four','five','six','seven']
>>> s=' '.join(nums)
>>> s
o/p= 'one two three four five six seven'
251 How will you remove a duplicate element from a list? Medium
Removing duplicates from a Python list can be achieved through several methods depending on whether you need to preserve original element order:
### 1. Using dict.fromkeys() (Preserves Order - Recommended):
Since Python 3.7, dictionaries maintain insertion order. Passing a list to dict.fromkeys() deduplicates elements while preserving their original order:
raw_list = [3, 1, 2, 3, 2, 4, 1]
unique_ordered = list(dict.fromkeys(raw_list))
print(unique_ordered) # Output: [3, 1, 2, 4]
### 2. Using set() (Fastest, but Discards Order):
Converting to a set operates in $O(n)$ time, but does not guarantee the original sequence:
unique_unordered = list(set(raw_list))
### 3. List Comprehension with Seen Tracker:
For complex objects that are not hashable (like dictionaries), iterate with an explicit seen set.
252 Can you explain the life cycle of a thread? Medium
python scripting interview questions
To create a thread, we create a class that we make override the run method of the thread class. Then, we instantiate it.
A thread that we just created is in the new state. When we make a call to start() on it, it forwards the threads for scheduling. These are in the ready state.
When execution begins, the thread is in the running state.
Calls to methods like sleep() and join() make a thread wait. Such a thread is in the waiting/blocked state.
When a thread is done waiting or executing, other waiting threads are sent for scheduling.
A running thread that is done executing terminates and is in the dead state.
253 Finally, tell us about bitwise operators in Python? Medium
python interview questions for freshers
These operate on values bit by bit.
AND (&) This performs & on each bit pair.
>>> 0b110 & 0b010
2
OR (|) This performs | on each bit pair.
>>> 3|2
3
XOR (^) This performs an exclusive-OR operation on each bit pair.
>>> 3^2
1
Binary One's Complement (~) This return s the one's complement of a value.
>>> ~2
-3
Binary Left-Shift (<<) This shifts the bits to the left by the specified amount.
>>> 1<<2
4
Here, 001 was shifted to the left by two places to get 100, which is binary for 4.
Binary Right-Shift (>>)
>>> 4>>2
1
254 What data types does Python support? Medium
Python provides us with five kinds of data types:
Numbers – Numbers use to hold numerical values.
>>> a=7.0
>>>
Strings – A string is a sequence of characters. We declare it using single or double quotes.
>>> title="Ayushi's Book"
Lists – A list is an ordered collection of values, and we declare it using square brackets.
>>> colors=['red','green','blue']
>>> type(colors)
<class 'list'>
Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, is that a tuple is immutable. This means that we cannot change a value in it.
>>> name=('Ayushi','Sharma')
>>> name[0]='Avery'
Traceback (most recent call last):
File "<pyshell#129>", line 1, in <module>
name[0]='Avery'
TypeError: 'tuple' object does not support item assignment
Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly braces.
>>> squares={1:1,2:4,3:9,4:16,5:25}
>>> type(squares)
<class 'dict'>
>>> type({})
<class 'dict'>
We can also use a dictionary comprehension:
>>> squares={x:x**2 for x in range(1,6)}
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
255 How would you convert a string into an int in Python? Medium
If a string contains only numerical characters, you can convert it into an integer using the int() function.
>>> int('227')
227
Let's check the types:
>>> type('227')
<class 'str'>
>>> type(int('227'))
<class 'int'>
256 How do you take input in Python? Medium
For taking input from the user, we have the function input(). In Python 2, we had another function raw_input().
The input() function takes, as an argument, the text to be displayed for the task:
>>> a=input('Enter a number')
Enter a number7
But if you have paid attention, you know that it takes input in the form of a string.
>>> type(a)
<class 'str'>
Multiplying this by 2 gives us this:
>>> a*=2
>>> a
'77'
So, what if we need to work on an integer instead?
We use the int() function for this.
>>> a=int(input('Enter a number'))
Enter a number7
Now when we multiply it by 2, we get this:
>>> a*=2
>>> a
14
257 What is a function? Medium
When we want to execute a sequence of statements, we can give it a name. Let's def ine a function to take two numbers and return the greater number.
>>> def greater(a,b):
return a is a>b else b
>>> greater(3,3.5)
3.5
258 What is recursion? Medium
When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid forming an infinite loop, we must have a base condition.
Let's take an example.
>>> def facto(n):
if n==1: return 1
return n*facto(n-1)
>>> facto(4)
24
259 What do you know about relational operators in Python? Medium
Top python interview questions with answers
Relational operators compare values.
Less than (<) If the value on the left is lesser, it return s True.
>>> 'hi'<'Hi'
False
Greater than (>) If the value on the left is greater, it return s True.
>>> 1.1+2.2>3.3
True
This is because of the flawed floating-point arithmetic in Python, due to hardware dependencies.
Less than or equal to (<=) If the value on the left is lesser than or equal to, it return s True.
>>> 3.0<=3
True
Greater than or equal to (>=) If the value on the left is greater than or equal to, it return s True.
>>> True>=False
True
Equal to (==) If the two values are equal, it return s True.
>>> {1,3,2,2}=={1,2,3}
True
Not equal to (!=) If the two values are unequal, it return s True.
>>> True!=0.1
True
>>> False!=0.1
True
260 What does the function zip() do? Medium
One of the less common functions with beginners, zip() return s an iterator of tuples.
>>> list(zip(['a','b','c'],[1,2,3]))
[('a', 1), ('b', 2), ('c', 3)]
Here, it pairs items from the two lists and creates tuples with those. But it doesn't have to be lists.
>>> list(zip(('a','b','c'),(1,2,3)))
[('a', 1), ('b', 2), ('c', 3)]
261 How can you declare multiple assignments in one statement? Medium
There are two ways to do this:
First –
>>> a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c respectively
Second –
>>> a=b=c=3 #This assigns 3 to a, b, and c
262 If you are ever stuck in an infinite loop, how will you break out of it? Medium
For this, we press Ctrl+C. This interrupts the execution. Let's create an infinite loop to demonstrate this.
>>> def counterfunc(n):
while(n==7):print(n)
>>> counterfunc(7)
Traceback (most recent call last):
File "<pyshell#332>", line 1, in <module>
counterfunc(7)
File "<pyshell#331>", line 2, in counterfunc
while(n==7):print(n)
KeyboardInterrupt
263 How is a .pyc file different from a .py file? Medium
While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-independent bytecode. Hence, we can execute it on any platform that supports the .pyc format. Python automatically generates it to improve performance(in terms of load time, not speed).
264 How many types of objects does Python support? Medium
Immutable objects- Those which do not let us modify their contents. Examples of these will be tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster.
>>> tuple=(1,2,4)
>>> tuple
(1, 2, 4)
>>> 2+4j
(2+4j)
Mutable objects – Those that let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower.
>>> [2,4,9]
[2, 4, 9]
>>> dict1={1:1,2:2}
>>> dict1
{1: 1, 2: 2}
While two equal immutable objects' reference variables share the same address, it is possible to create two mutable objects with the same content.
265 When is the else part of a try-except block executed? Medium
In an if-else block, the else part is executed when the condition in the if-statement is False. But with a try-except block, the else part executes only if no exception is raised in the try part.
266 Explain join() and split() in Python? Medium
1)join() lets us join characters from a string together by a character we specify.
>>> ','.join('12345')
'1,2,3,4,5'
2) split() lets us split a string around the character we specify.
>>> '1,2,3,4,5'.split(',')
['1', '2', '3', '4', '5']
267 Explain a few methods to implement Functionally Oriented Programming in Python? Medium
Sometimes, when we want to iterate over a list, a few methods come in handy.
a. filter()
Filter lets us filter in some values based on conditional logic.
>>> list(filter(lambda x:x>5,range(8)))
[6, 7]
b. map()
Map applies a function to every element in an iterable.
>>> list(map(lambda x:x**2,range(8)))
[0, 1, 4, 9, 16, 25, 36, 49]
c. reduce()
Reduce repeatedly reduces a sequence pair-wise until we reach a single value.
>>> from functools import reduce
>>> reduce(lambda x,y:x-y,[1,2,3,4,5])
-13
268 Is del the same as remove()? What are they? Medium
del and remove() are methods on lists/ ways to eliminate elements.
>>> list=[3,4,5,6,7]
>>> del list[3]
>>> list
[3, 4, 5, 7]
>>> list.remove(5)
>>> list
[3, 4, 7]
While del lets us delete an element at a certain index, remove() lets us remove an element by its value.
269 How do you open a file for writing? Medium
Let's create a text file on our Desktop and call it tabs.txt. To open it to be able to write to it, use the following line of code-
>>> file=open('tabs.txt','w')
This opens the file in writing mode. You should close it once you're done.
>>> file.close()
270 Difference between the append() and extend() methods of a list. Medium
The methods append() and extend() work on lists. While append() adds an element to the end of the list, extend adds another list to the end of a list.
Let's take two lists.
>>> list1,list2=[1,2,3],[5,6,7,8]
This is how append() works:
>>> list1.append(4)
>>> list1
[1, 2, 3, 4]
And this is how extend() works:
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]
271 What are the different file-processing modes with Python? Medium
We have the following modes-
read-only – 'r'
write-only – 'w'
read-write – 'rw'
append – 'a'
We can open a text file with the option 't'. So to open a text file to read it, we can use the mode 'rt'. Similarly, for binary files, we use 'b'.
272 What does the map() function do? Medium
map() executes the function we pass to it as the first argument; it does so on all elements of the iterable in the second argument. Let's take an example, shall we?
>>> for i in map(lambda i:i**3, (2,3,7)):
print(i)
This gives us the cubes of the values 2, 3, and 7.
273 How will you convert an integer to a Unicode character? Medium
This is simple. All we need is the chr(x) built-in function. See how.
>>> chr(52)
'4'
>>> chr(49)
'1'
>>> chr(67)
'C'
274 So does recursion cause any trouble? Medium
Sure does:
Needs more function calls.
Each function call stores a state variable to the program stack- consumes memory, can cause memory overflow.
Calling a function consumes time.
275 What good is recursion? Medium
Recursion is a programming technique where a function solves a problem by calling itself with smaller sub-instances of the same problem until reaching a base case.
### Real-World Use Cases Where Recursion Excels:
- Tree and Graph Traversal:
Navigating hierarchical data structures like the DOM tree, AST syntax trees, or JSON configurations.
- Divide-and-Conquer Algorithms:
High-performance sorting algorithms like Merge Sort and Quick Sort, or Binary Search.
- Filesystem Traversal:
Scanning nested directories and subdirectories (os.walk).
### Python Caveats:
- Python does not perform Tail-Call Optimization (TCO).
- Python enforces a default maximum recursion depth (typically 1,000 frames) to guard against stack overflows:
sys.getrecursionlimit(). For deeply nested iterations, iterative loops with explicit stacks are preferred.
276 Can you remove the whitespaces from the string "aaa bbb ccc ddd eee"? Medium
I can think of three ways to do this.
Using join-
>>> s='aaa bbb ccc ddd eee'
>>> s1=".join(s.split())
>>> s1
'aaabbbcccdddeee'
Using a list comprehension–
>>> s='aaa bbb ccc ddd eee'
>>> s1=str(".join(([i for i in s if i!=' '])))
>>> s1
'aaabbbcccdddeee'
Using replace()-
>>> s='aaa bbb ccc ddd eee'
>>> s1 = s.replace(' ',")
>>> s1
'aaabbbcccdddeee'
277 How do you get the current working directory using Python? Medium
Working on software with Python, you may need to read and write files from various directories. To find out which directory we're presently working under, we can borrow the getcwd() method from the os module.
>>> import os
>>> os.getcwd()
'C:\\Users\\Raj\\AppData\\Local\\Programs\\Python\\Python37-32'
278 What are the file-related modules we have in Python? Medium
Python provides rich standard library modules for interacting with files, paths, and storage systems:
pathlib(Modern Standard): Object-oriented filesystem paths (Path('dir') / 'file.txt').os&os.path: Low-level operating system calls (os.remove,os.listdir,os.mkdir).shutil: High-level file operations (copying entire directoriescopytree(), removing directory treesrmtree()).io: In-memory text and binary stream buffers (io.StringIO,io.BytesIO).tempfile: Securely generates temporary files and folders (NamedTemporaryFile) cleaned up upon exit.csv/json: Specialized parsers for structured data file formats.
279 What is Virtualenv in Python? Medium
virtualenv is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need. It can be used standalone, in place of Pipenv.
Install virtualenv via pip: $ pip install virtualenv.
280 What does the Python nonlocal statement do (in Python 3.0 and later)? Medium
In short, it lets you assign values to a variable in an outer (but non-global) scope.
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
For example the counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
281 What are the wheels and eggs? What is the difference? Medium
Wheel and Egg are both packaging formats that aim to support the use case of needing an install artifact that doesn't require building or compilation, which can be costly in testing and production workflows.
The Egg format was introduced by setuptools in 2004, whereas the Wheel format was introduced by PEP 427 in 2012.
Wheel is currently considered the standard for built and binary packaging for Python.
Here's a breakdown of the import ant differences between Wheel and Egg.
Wheel has an official PEP. Egg did not.
Wheel is a distribution format, i.e a packaging format. 1 Egg was both a distribution format and a runtime installation format (if left zipped), and was designed to be import able.
Wheel archives do not include .pyc files. Therefore, when the distribution only contains Python files (i.e. no compiled extensions), and is compatible with Python 2 and 3, it's possible for a wheel to be "universal", similar to an sdist.
Wheel uses PEP376-compliant .dist-info directories. Egg used .egg-info.
Wheel has a richer file naming convention. A single wheel archive can indicate its compatibility with a number of Python language versions and implementations, ABIs, and system architectures.
Wheel is versioned. Every wheel file contains the version of the wheel specification and the implementation that packaged it.
Wheel is internally organized by sysconfig path type, therefore making it easier to convert to other formats.
282 What is webpack? Medium
Webpack is a build tool that puts all of your assets, including Javascript, images, fonts, and CSS, in a dependency graph. Webpack lets you use require() in your source code to point to local files, like images, and decide how they're processed in your final Javascript bundle, like replacing the path with a URL pointing to a CDN.
283 Name some benefits of using webpack? Medium
Webpack and static assets in a dependency graph offers many benefits. Here's a few:
Dead asset elimination. This is killer, especially for CSS rules. You only build the images and CSS into your dist/ folder that your application actually needs.
Easier code splitting. For example, because you know that your file Homepage.js only requires specific CSS files, Webpack could easily build a homepage.css file to greatly reduce initial file size.
You control how assets are processed. If an image is below a certain size, you could base64 encode it directly into your Javascript for fewer HTTP requests. If a JSON file is too big, you can load it from a URL. You can require('./style.less') and it's automaticaly parsed by Less into vanilla CSS.
Stable production deploys. You can't accidentally deploy code with images missing, or outdated styles.
Webpack will slow you down at the start, but give you great speed benefits when used correctly. You get hot page reloading. True CSS management. CDN cache busting because Webpack automatically changes file names to hashes of the file contents, etc.
Webpack is the main build tool adopted by the React community.
284 Name some plugins you think are very important and helpful? Medium
CommonsChunkPlugin – creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points.
DefinePlugin – allows you to create global constants which can be configured at compile time.
HtmlWebpackPlugin – simplifies creation of HTML files to serve your webpack bundles.
ExtractTextWebpackPlugin – Extract text from a bundle, or bundles, into a separate file.
CompressionWebpackPlugin – Prepare compressed versions of assets to serve them with Content-Encoding.
285 Webpack gives us a dependency graph. What does that mean? Medium
Any time one file depends on another, webpack treats this as a dependency. This allows webpack to take non-code assets, such as images or web fonts, and also provide them as dependencies for your application.
Webpack lets you use require() on local "static assets":
<img src={ require('../../assets/logo.png') } />
When webpack processes your application, it starts from a list of modules def ined on the command line or in its config file. Starting from these entry points, webpack recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles – often, just one – to be loaded by the browser.
The require('logo.png') source code never actually gets executed in the browser (nor in Node.js). Webpack builds a new Javascript file, replacing require() calls with valid Javascript code, such as URLs. The bundled file is what's executed by Node or the browser.
286 How to make a chain of function decorators? Medium
How can I make two decorators in Python that would do the following?
@makebold
@makeitalic
def say():
return "Hello"
which should return:
"<b><i>Hello</i></b>"
Answer:
Consider:
from functools import wraps
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapped
def makeitalic(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
@makebold
@makeitalic
def log(s):
return s
print(hello)() # return s "<b><i>hello world</i></b>"
print(hello.__name__ # with functools.wraps)() this return s "hello"
print(log)('hello') # return s "<b><i>hello</i></b>"
287 What is the difference between @staticmethod and @classmethod? Medium
A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It's def inition is immutable via inheritance.
class C:
@staticmethod
def f(arg1, arg2, ...): ...
A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. Its def inition follows Sub class, not Parent class, via inheritance.
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
If your method accesses other variables/methods in your class then use @classmethod.
288 What's the difference between a Python module and a Python package? Medium
Any Python file is a module, its name being the file's base name without the .py extension.
import my_module
A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional init.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own init.py file.
Packages are modules too. They are just packaged up differently; they are formed by the combination of a directory plus init.py file. They are modules that can contain other modules.
from my_package.timing.danger.internets import function_of_love
289 Is it a good idea to use multi-thread to speed your Python code? Medium
Python doesn't allow multi-threading in the truest sense of the word. It has a multi-threading package but if you want to multi-thread to speed your code up, then it's usually not a good idea to use it.
Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution.
290 How do I write a function with output parameters (call by reference)? Medium
In Python arguments are passed by assignment. When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object.
If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method (like b = b + 1), the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.
So to achieve the desired effect your best choice is to return a tuple containing the multiple results:
def func2(a, b):
a = 'new-value' # a and b are local names
b = b + 1 # assigned to new objects
return a, b # return new values
x, y = 'old-value', 99
x, y = func2(x, y)
print(x, y)
291 Whenever you exit Python, is all memory de-allocated? Medium
The answer here is no. The modules with circular references to other objects, or to objects referenced from global namespaces, aren't always freed on exiting Python. Plus, it is impossible to de-allocate portions of memory reserved by the C library.
292 What is the purpose of the single underscore "_" variable in Python? Medium
has 4 main conventional uses in Python:
To hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
For translation lookup in i18n (see the gettext documentation for example), as in code like: raise forms.ValidationError(_("Please enter a correct username"))
As a general purpose "throwaway" variable name to indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like: label, has_label, _ = text.partition(':').
As part of a function def inition (using either def or lambda), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like: callback = lambda _: True
293 How is set() implemented internally? I've seen people say that set objects in Python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have? Medium
Indeed, CPython's sets are implemented as something like dictionaries with dummy values (the keys being the members of the set), with some optimization(s) that exploit this lack of values.
So basically a set uses a hashtable as its underlying data structure. This explains the O(1) membership checking, since looking up an item in a hashtable is an O(1) operation, on average.
Also, it worth to mention when people say sets have O(1) membership-checking, they are talking about the average case. In the worst case (when all hashed values collide) membership-checking is O(n).
294 What is MRO in Python? How does it work? Medium
Method Resolution Order (MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass.
In Python, method resolution order def ines the order in which the base classes are searched when executing a method. First, the method or attribute is searched within a class and then it follows the order we specified while inheriting. This order is also called Linearization of a class and set of rules are called MRO (Method Resolution Order). While inheriting from another class, the interpreter needs a way to resolve the methods that are being called via an instance. Thus we need the method resolution order.
Python resolves method and attribute lookups using the C3 linearisation of the class and its parents. The C3 linearisation is neither depth-first nor breadth-first in complex multiple inheritance hierarchies.
295 What is the difference between old style and new style classes in Python? Medium
Declaration-wise:
New-style classes inherit from object, or from another new-style class.
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass):
pass
Old-style classes don't.
class OldStyleClass():
pass
Python 3 Note:
Python 3 doesn't support old style classes, so either form noted above results in a new-style class.
Also, MRO (Method Resolution Order) changed:
Classic classes do a depth first search from left to right. Stop on first match. They do not have the mro attribute.
New-style classes MRO is more complicated to synthesize in a single English sentence. One of its properties is that a Base class is only searched for once all its Derived classes have been. They have the mro attribute which shows the search order.
Some other notes:
New style class objects cannot be raised unless derived from Exception.
Old style classes are still marginally faster for attribute lookup.
296 How are arguments passed by value or by reference in Python? Medium
Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
In Python, arguments are passed by reference, i.e., reference to the actual object is passed.
def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
print(arr) #Output: => [1, 2, 3]
appendNumber(arr)
print(arr) #Output: => [1, 2, 3, 4]
297 What is a boolean in Python? Medium
Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false.
Python bool() is the method used to convert a value to a boolean value.
1
Syntax for bool() method: bool([a])
298 Name some of the built-in modules in Python? Medium
Python's "batteries included" philosophy includes an extensive set of built-in standard library modules:
- Data Structures & Utilities:
collections(defaultdict,Counter),itertools,functools,dataclasses. - System & OS:
sys,os,pathlib,subprocess,platform. - Math & Numeric:
math,random,decimal,statistics. - Date & Time:
datetime,time,calendar. - Data Serialization:
json,csv,pickle,sqlite3. - Networking & Web:
urllib,http,socket,email. - Asynchronous & Concurrency:
asyncio,threading,multiprocessing,concurrent.futures. - Testing & Debugging:
unittest,pdb,logging.
299 How to remove values from a Python array? Medium
The elements can be removed from a Python array using remove() or pop() function. The difference between pop() and remove() will be explained in the below example.
Example:
x = arr.array('d', [ 1.0, 2.2, 3.4, 4.8, 5.2, 6.6, 7.3])
print(x.pop())
print(x.pop(3))
x.remove(1.0)
print(a)
Output:
7.3
4.8
array('d', [2.2, 3.4, 5.2, 6.6])
300 What is Try Block? Medium
A try block in Python encapsulates code that may potentially raise a runtime exception, allowing your application to handle errors gracefully without crashing:
try:
with open("config.json", "r") as f:
config = json.load(f)
except FileNotFoundError:
print("Configuration file missing. Loading defaults.")
config = {"env": "development"}
except json.JSONDecodeError as err:
print(f"Malformed JSON: {err}")
else:
print("Configuration loaded successfully.")
finally:
print("Initialization sequence completed.")
### The 4 Blocks:
try: Code being executed.except: Catches and handles specific exceptions.else: Executes only if thetryblock succeeded with no exceptions.finally: Executes always, regardless of success or failure (ideal for resource cleanup).
301 How can we access a module written in Python from C? Medium
Python modules can be imported and executed from C/C++ applications via the official Python C API (#include <Python.h>):
#include <Python.h>
void run_python_logic() {
Py_Initialize();
// Import the module
PyObject *pModule = PyImport_ImportModule("my_module");
if (pModule != NULL) {
// Retrieve and execute function
PyObject *pFunc = PyObject_GetAttrString(pModule, "my_function");
if (pFunc && PyCallable_Check(pFunc)) {
PyObject *pValue = PyObject_CallNoArgs(pFunc);
Py_XDECREF(pValue);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
Py_Finalize();
}
302 Write a program to count the number of capital letters in a file? Medium
Here is a memory-efficient Python program to count uppercase capital letters in a file:
def count_uppercase_letters(filepath: str) -> int:
"""Counts uppercase letters in a file line-by-line for memory efficiency."""
total_capitals = 0
with open(filepath, "r", encoding="utf-8") as file:
for line in file:
total_capitals += sum(1 for char in line if char.isupper())
return total_capitals
# Example execution
count = count_uppercase_letters("document.txt")
print(f"Total capital letters: {count}")
### Why Line-by-Line Iteration Matters:
Reading the entire file with .read() loads the full content into RAM simultaneously. Iterating line-by-line (for line in file) processes text in a memory-efficient stream, allowing the script to effortlessly process multi-gigabyte files without crashing.
303 Write a program to display the Fibonacci sequence in Python? Medium
# Displaying Fibonacci sequence
n = 10
# first two terms
n0 = 0
n1 = 1
#Count
x = 0
# check if the number of terms is valid
if n <= 0:
print("Enter positive integer")
elif n == 1:
print("Numbers in Fibonacci sequence upto",n,":")
print(n0)
else:
print("Numbers in Fibonacci sequence upto",n,":")
while x < n:
print(n0,end=', ')
nth = n0 + n1
n0 = n1
n1 = nth
x += 1
Output:
1
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
304 Write a program in Python to produce Star triangle? Medium
The code to produce star triangle is as follows:
def pyfun(r):
for a in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfun(9)
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
305 Write a program to check whether the given number is prime or not? Medium
The code to check prime number is as follows:
# program to check the number is prime or not
n1 = 409
# num1 = int(input("Enter any one number: "))
# prime number is greater than 1
if n1 > 1:
# check the following factors
for x is in range of(2,num1):
if (n1 % x) == 0:
print(n1,"is not a prime number")
print(x,"times",n1//x,"is",num)
break
else:
print(n1,"is a prime number")
# if input number is smaller than
# or equal to the value 1, then it is not prime number
else:
print(n1,"is not a prime number")
Output:
1
409 is a prime number
306 Write Python code to check the given sequence is a palindrome or not? Medium
# Python code to check a given sequence
# is palindrome or not
my_string1 = 'MOM'
My_string1 = my_string1.casefold()
# reverse the given string
rev_string1 = reversed(my_string1)
# check whether the string is equal to the reverse of it or not
if list(my_string1) == list(rev_string1):
print("It is a palindrome")
else:
print("It is not a palindrome")
Output:
1
it is a palindrome
307 Write Python code to sort a numerical dataset? Medium
The code to sort a numerical dataset is as follows:
list = [ "13", "16", "1", "5" , "8"]
list = [int(x) for x in the list]
list.sort()
print(list)
Output:
1
1, 5, 8, 13, 16
All 307 questions loaded
Frequently Asked Questions About Python Interviews
What do hiring managers evaluate in Python technical rounds?
Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.
What are the best interview tips for practicing Python questions?
Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.