Since programming fundamentals like OOP, API development, and database design remain the same
across languages, transitioning between .NET and Python becomes easier. Currently I am also studying
AI/ML, where Python is widely used, so I am strengthening my Python knowledge as well.
Python is widely used for backend development, automation, and AI/ML. Its simplicity and large
ecosystem make development faster.
What are Python’s key features?
Interpreted language
Dynamically typed
Object-oriented
Large standard library
Cross-platform
Easy to read and write
Difference between List and Tuple
List Tuple
Mutable Immutable
Uses [] Uses ()
Slower Faster
Can modify elements Cannot modify
Example:
my_list = [1,2,3]
my_tuple = (1,2,3)
3️What is a Dictionary in Python?
A dictionary stores key-value pairs.
Example:
employee = {
"name": "John",
"age": 30
}
Access:
print(employee["name"])
4️ What is List Comprehension?
A concise way to create lists.
Example:
numbers = [x*x for x in range(5)]
Output:
[0,1,4,9,16]
5️ What are *args and **kwargs?
Used to pass variable number of arguments.
Example:
def add(*args):
return sum(args)
Example kwargs:
def info(**kwargs):
print(kwargs)
6️ What is a Lambda Function?
Anonymous function with a single expression.
Example:
square = lambda x: x*x
print(square(5))
Output: 25
7️ Difference between Deep Copy and Shallow Copy
Shallow Copy
Copies reference.
Deep Copy
Creates new object including nested objects.
Example:
import copy
a = [[1,2],[3,4]]
b = [Link](a)
8️ What is the Global Interpreter Lock (GIL)?
GIL allows only one thread to execute Python bytecode at a time, which limits true
parallelism in CPU-bound tasks.
However, it does not affect I/O-bound tasks much.
9️ What are Python Decorators?
Decorators modify the behavior of a function without changing its code.
Example:
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
10 What are Generators?
Generators produce values one at a time using yield.
Example:
def numbers():
for i in range(5):
yield i
Benefit: memory efficient
1 What is the difference between is and ==?
Operator Meaning
== compares values
is compares memory location
Example:
a = [1,2]
b = [1,2]
print(a == b) # True
print(a is b) # False
12 What is Exception Handling in Python?
Used to handle runtime errors.
Example:
try:
x = 10/0
except ZeroDivisionError:
print("Cannot divide by zero")
13. What are Python Modules and Packages?
Module
A single Python file.
Package
A collection of modules.
Example:
[Link] → module
utils/ → package
14. Difference between Multithreading and Multiprocessing
Multithreading Multiprocessing
Uses threads Uses separate processes
Limited by GIL True parallelism
Good for I/O tasks Good for CPU tasks
15 What are Python Virtual Environments?
Used to isolate dependencies for different projects.
Command:
python -m venv env
Activate:
env\Scripts\activate
⭐ BONUS question (often asked)
Q: Why Python is preferred for AI/ML?
Answer:
Huge ecosystem (NumPy, Pandas, TensorFlow)
Simple syntax
Fast prototyping
Large community support
🔥 One trick for your interview
Since your background is .NET, interviewers may ask:
“How easy is it for you to switch from .NET to Python?”
Best answer:
“Since programming concepts like OOP, APIs, and database design remain the same, switching
languages is mainly about syntax. My strong backend experience helps me adapt quickly.”
10 scenario-based Python questions TCS asks experienced candidates.
Question:
You need to process a 10GB log file in Python without running out of memory. How will you do
it?
Answer approach:
Use generators or streaming
Read the file line by line
Example:
with open("[Link]") as f:
for line in f:
process(line)
Why:
This avoids loading the whole file into memory.
2️ Scenario: API Performance Issue
Question:
Your Python API is slow when multiple users access it. What steps will you take?
Answer approach:
Use caching (Redis / in-memory cache)
Optimize database queries
Use async programming
Implement load balancing
Mention frameworks like FastAPI / Flask if needed.
3️ Scenario: Handling Multiple Tasks
Question:
You need to fetch data from 100 APIs simultaneously. How will you implement this in Python?
Answer approach:
Use asyncio or multithreading.
Example:
import asyncio
import aiohttp
Why:
Async I/O handles multiple requests efficiently.
4️ Scenario: Memory Optimization
Question:
Your Python program consumes too much memory. How will you optimize it?
Answer approach:
Use generators instead of lists
Delete unused objects
Use gc module
Use efficient data structures
Example:
(x*x for x in range(1000000))
Instead of
[x*x for x in range(1000000)]
5️ Scenario: Duplicate Data Removal
Question:
You receive millions of records and need to remove duplicates efficiently.
Answer approach:
Use set or dictionary.
Example:
data = [1,2,3,2,1]
unique = list(set(data))
6️ Scenario: Error Handling in Production
Question:
Your Python application crashes due to unexpected errors. What will you do?
Answer approach:
Implement proper exception handling
Add logging
Monitor using tools
Example:
import logging
try:
process()
except Exception as e:
[Link](e)
7️ Scenario: Background Jobs
Question:
You need to run background tasks like sending emails or generating reports.
Answer approach:
Use task queues like:
Celery
RabbitMQ
Redis
This avoids blocking the main application.
8️ Scenario: Database Optimization
Question:
Your Python application using SQL is slow. How will you optimize it?
Answer approach:
Use indexes
Optimize SQL queries
Avoid unnecessary joins
Use connection pooling
This is important because your profile already includes SQL Server and PL/SQL experience.
9 Scenario: Secure Coding
Question:
How will you prevent SQL injection in Python applications?
Answer approach:
Use parameterized queries.
Example:
[Link]("SELECT * FROM users WHERE id=%s", (user_id,))
Avoid:
"SELECT * FROM users WHERE id=" + user_id
Scenario: Code Maintainability
Question:
Your Python codebase is becoming difficult to maintain. What will you do?
Answer approach:
Follow OOP principles
Use design patterns
Write modular code
Add unit tests
Example tools:
pytest
unittest
⭐ One scenario they often ask experienced developers
“How would you design a scalable Python backend system?”
Expected points:
REST APIs
Microservices architecture
Database optimization
Caching
Containerization (Docker)
✅ Since you have 6 years experience in .NET + SQL, the interviewer may also ask cross-
language questions like:
“Compare Python and C# performance”
“When would you choose Python over .NET?”
“How will you migrate a .NET service to Python?
Reverse a String
Question: Reverse a string without using built-in functions.
def reverse_string(s):
rev = ""
for char in s:
rev = char + rev
return rev
print(reverse_string("hello"))
Output: olleh
2️ Find Duplicate Elements in a List
def find_duplicates(lst):
seen = set()
duplicates = set()
for num in lst:
if num in seen:
[Link](num)
else:
[Link](num)
return list(duplicates)
print(find_duplicates([1,2,3,2,4,5,1]))
Output: [1,2]
3️ Fibonacci Series
def fibonacci(n):
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(10)
Output:
0 1 1 2 3 5 8 13 21 34
4️ Check if a String is a Palindrome
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))
Output: True
5️ Count Frequency of Characters in a String
def char_frequency(s):
freq = {}
for char in s:
freq[char] = [Link](char,0) + 1
return freq
print(char_frequency("hello"))
Output:
{'h':1,'e':1,'l':2,'o':1}
6️ Find the Largest Element in a List
def find_max(lst):
max_num = lst[0]
for num in lst:
if num > max_num:
max_num = num
return max_num
print(find_max([5,8,2,10,3]))
Output: 10
7️ Remove Duplicates from a List
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1,2,2,3,4,4,5]))
Output: [1,2,3,4,5]
8️ Check if Two Strings are Anagrams
def is_anagram(a,b):
return sorted(a) == sorted(b)
print(is_anagram("listen","silent"))
Output: True
9️ Find Missing Number in an Array
Example array from 1 to n.
def missing_number(arr,n):
expected = n*(n+1)//2
actual = sum(arr)
return expected - actual
print(missing_number([1,2,3,5],5))
Output: 4
10 Sort a List without Using sort()
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0,n-i-1):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
print(bubble_sort([5,3,8,1]))
Output: [1,3,5,8]
Reverse Words in a Sentence (Not Characters)
Question
Input:
"Python is powerful"
Output:
"powerful is Python"
Many candidates mistakenly reverse characters.
Correct Code
def reverse_words(sentence):
words = [Link]()
return " ".join(words[::-1])
print(reverse_words("Python is powerful"))
Output:
powerful is Python
2️ Find the First Non-Repeating Character
Question
Input:
"programming"
Output:
Solution
from collections import Counter
def first_unique(s):
count = Counter(s)
for char in s:
if count[char] == 1:
return char
print(first_unique("programming"))
3️Swap Two Numbers Without Using a Temporary Variable
Many candidates overcomplicate this.
Python Solution
a = 5
b = 10
a, b = b, a
print(a, b)
Output:
10 5
Python supports tuple unpacking.
4️ Flatten a Nested List
Input
[1, [2,3], [4,[5,6]]]
Expected output:
[1,2,3,4,5,6]
Solution
def flatten(lst):
result = []
for item in lst:
if isinstance(item,list):
[Link](flatten(item))
else:
[Link](item)
return result
print(flatten([1,[2,3],[4,[5,6]]]))
This tests recursion knowledge.
5️Python Output Question (Very Common Trap)
Question
What will be the output?
a = [1,2,3]
b = a
[Link](4)
print(a)
Most candidates say:
[1,2,3]
❌ Wrong.
Correct Output
[1,2,3,4]
Because lists are mutable and both variables reference the same object.
One extremely common trap question
What will be the output?
def add_item(item, lst=[]):
[Link](item)
return lst
print(add_item(1))
print(add_item(2))
Most people say:
[1]
[2]
❌ Wrong.
Actual output:
[1]
[1,2]
Because default mutable arguments are shared between function calls.
7 common trap questions and the smartest way to answer them.
1 You have 6 years of experience. Why are you still working on the
same technology?
Trap: They want to see if you are stagnant.
Smart answer:
“While my core expertise has been in .NET backend development, I’ve consistently expanded
my skills by working on API design, database optimization, and automation. Recently I have
also been strengthening my Python skills because of its growing role in backend services and
AI/ML.”
This shows growth mindset.
2 Why should we hire you when many candidates have Python as their
primary skill?
Trap: They compare you with stronger Python candidates.
Smart answer:
“Apart from learning Python, I bring strong backend engineering experience including OOP,
REST API design, and database optimization with SQL Server and PL/SQL. These fundamentals
apply across languages, so I can quickly contribute while adapting to Python-based systems.”
This shows transferable skills.
3 Explain a project where you failed.
Trap: They test honesty and accountability.
Smart answer structure
1. Situation
2. What went wrong
3. What you learned
Example:
“In one project we underestimated performance requirements which caused delays in production.
I later worked on query optimization and implemented caching, which improved performance
significantly. That experience helped me plan scalability better in later projects.”
Never say “I never failed.”
4 If we give you a technology you have never used before, how long
will you take to learn it?
Trap: They test adaptability.
Smart answer:
“Since programming concepts like OOP, APIs, and database design are common across
languages, I usually focus on understanding the syntax and ecosystem first. I believe I can
become productive in a few weeks while continuously improving through real project work.”
5 What is something in Python you don’t know?
Trap: If you claim you know everything, it looks fake.
Smart answer:
“While I’m comfortable with core Python concepts like data structures, OOP, and scripting, I am
still exploring advanced topics such as deep performance tuning and large-scale distributed
processing.”
Shows honesty + learning attitude.
6 Why are you leaving your current company?
Trap: They check negativity.
Never complain.
Smart answer:
“I’ve had a great learning experience in my current organization. However, I’m now looking for
opportunities where I can work on larger systems and expand my skills in technologies like
Python and modern backend architectures.”
7 What will you do if you are stuck on a problem for a long time?
Trap: They check teamwork and problem solving.
Smart answer:
“First I try to analyze the problem by breaking it into smaller parts and checking logs or
documentation. If I’m still stuck, I discuss it with teammates or seniors. Collaboration often
helps resolve issues faster and improves overall team productivity.”
If this question is asked in an interview at Tata Consultancy Services, they are testing your
system design thinking and migration approach, not just Python knowledge. You should
answer step-by-step like an architect.
Here is a strong interview answer structure.
How to Migrate a .NET Service to Python
1 Understand the Existing .NET Service
First, analyze the current .NET architecture.
Check:
Business logic
APIs/endpoints
Database interactions
External integrations
Authentication and security
Example stack:
[Link] Web API
SQL Server
IIS hosting
Understanding this helps avoid breaking functionality.
2 Identify Python Framework
Choose a suitable Python framework depending on the application.
Common choices:
Flask – lightweight microservices
FastAPI – high performance APIs
Django – full-stack applications
For most API migrations, FastAPI or Flask works well.
3 Replicate API Endpoints
Rewrite the existing .NET controllers as Python API endpoints.
Example:
.NET API
[HttpGet]
public IActionResult GetUsers()
{
return Ok([Link]());
}
Python (FastAPI)
from fastapi import FastAPI
app = FastAPI()
@[Link]("/users")
def get_users():
return user_service.get_users()
Goal: Keep API contracts same so front-end is unaffected.
4 Migrate Business Logic
Rewrite core logic using Python modules.
Use:
Python classes
OOP principles
Service layers
Example:
controllers
services
repositories
models
Similar layered architecture as .NET.
5 Database Integration
Since you already know SQL Server and PL/SQL, highlight this.
Options:
Use SQLAlchemy ORM
Use raw SQL queries
Maintain same database schema
Example:
from sqlalchemy import create_engine
engine = create_engine("mssql+pyodbc://connection_string")
6 Implement Security & Authentication
Migrate:
JWT authentication
OAuth if used
API validation
Python libraries:
python-jose
passlib
[Link]
7 Testing the New Service
Perform:
Unit testing
Integration testing
API testing
Tools:
pytest
Postman
Goal: Ensure Python service behaves exactly like the .NET service.
8 Deployment
Deploy using modern tools:
Docker containers
Kubernetes
CI/CD pipeline
Python apps can run with:
Uvicorn
Gunicorn
Strong Closing Line (Very Important)
End your answer like this:
“During migration, I would prefer a phased approach where both services run in parallel. This
ensures minimal downtime and allows gradual validation before completely switching
from .NET to Python.”
This shows production-level thinking.
Bonus: Why companies migrate from .NET to Python
You can add:
Faster development
Better ecosystem for AI/ML
Simpler syntax
Strong open-source libraries
1️ Mutable vs Immutable Objects
Mutable
Objects whose value can be changed after creation.
Examples:
List
Dictionary
Set
Example:
my_list = [1,2,3]
my_list.append(4)
print(my_list)
Output:
[1,2,3,4]
The original object changes in memory.
Immutable
Objects whose value cannot be changed after creation.
Examples:
int
string
tuple
Example:
x = "hello"
x = x + " world"
print(x)
A new object is created, the original string is not modified.
Quick Interview Table
Mutable Immutable
Can change value Cannot change value
Mutable Immutable
Same memory object modified New object created
Examples: list, dict Examples: int, str, tuple
2️ Shallow Copy vs Deep Copy
This question tests memory references.
Shallow Copy
Copies the reference of nested objects.
Example:
import copy
a = [[1,2],[3,4]]
b = [Link](a)
b[0][0] = 100
print(a)
Output:
[[100,2],[3,4]]
Because inner list reference is shared.
Deep Copy
Creates completely independent copies.
Example:
import copy
a = [[1,2],[3,4]]
b = [Link](a)
b[0][0] = 100
print(a)
Output:
[[1,2],[3,4]]
Original object remains unchanged.
Quick Comparison
Shallow Copy Deep Copy
Copies references Copies full objects
Faster Slower
Changes may affect original Completely independent
3️ Generators vs Lists
This question checks memory optimization knowledge.
List
Stores all values in memory at once.
Example:
numbers = [x*x for x in range(5)]
print(numbers)
Output:
[0,1,4,9,16]
Generator
Produces values one at a time using yield.
Example:
def squares():
for i in range(5):
yield i*i
for num in squares():
print(num)
Why Generators Are Powerful
Example scenario:
Processing millions of records or large files.
Generators are memory efficient because they produce values on demand.
Quick Comparison
Generator List
Uses yield Uses list syntax
Memory efficient Stores entire list
Lazy evaluation Immediate evaluation
One interview trick question
Which is better: generator or list?
Correct answer:
“Generators are better for large datasets and streaming data because they are memory efficient,
while lists are better when we need random access or repeated iterations.”
is vs ==
==
Checks value equality.
a = [1,2,3]
b = [1,2,3]
print(a == b)
Output:
True
Because the values are the same.
is
Checks memory location (object identity).
print(a is b)
Output:
False
Because both lists are different objects in memory.
Interview Line
"== compares values, while is checks whether two variables refer to the same object in
memory."
2️ Python Memory Management & Garbage Collection
Python automatically manages memory using:
Reference counting
Garbage collection
Example:
a = [1,2,3]
b = a
del a
The object is not deleted because b still references it.
Once reference count becomes zero, Python frees the memory.
3️Decorators
Decorators allow you to modify a function's behavior without changing its code.
Example:
def logger(func):
def wrapper():
print("Function started")
func()
print("Function ended")
return wrapper
@logger
def say_hello():
print("Hello")
say_hello()
Output:
Function started
Hello
Function ended
4️Iterators vs Generators
Iterator
Object with:
__iter__()
__next__()
Example:
nums = iter([1,2,3])
print(next(nums))
print(next(nums))
Generator
Simpler way to create iterators using yield.
Example:
def count():
for i in range(3):
yield i
Generators automatically manage iterator behavior.
5️ Python GIL (Global Interpreter Lock)
Very common interview question.
What it is
GIL ensures only one thread executes Python bytecode at a time.
Impact
Limits true parallel execution for CPU tasks
Does not significantly affect I/O-bound tasks
Example:
API calls → fine with threads
Heavy computation → better with multiprocessing
Smart Interview Tip
After answering these questions, you can impress the interviewer by connecting it with real-
world scenarios:
Example:
“Generators are especially useful when processing large log files or streaming data because they
avoid loading the entire dataset into memory.”
For 5–7 years experienced backend developers, interviewers (including at Tata Consultancy
Services) focus heavily on OOP concepts in Python. They want to see whether you understand
design, structure, and maintainable code, not just syntax.
Below are 10 very important Python OOP questions with clear explanations you can give in
interviews.
1️ What are the four pillars of OOP?
Answer
1. Encapsulation – Wrapping data and methods into a class
2. Abstraction – Hiding internal implementation details
3. Inheritance – Creating a new class from an existing class
4. Polymorphism – Same method behaving differently
Example:
class Animal:
def speak(self):
print("Animal sound")
2️ What is a Class and Object in Python?
Class
Blueprint for creating objects.
Object
Instance of a class.
Example:
class Car:
def __init__(self,name):
[Link] = name
car1 = Car("BMW")
Here:
Car → class
car1 → object
3️ What is __init__ in Python?
__init__ is a constructor that runs automatically when an object is created.
Example:
class Person:
def __init__(self,name):
[Link] = name
Used to initialize object attributes.
4️ What is Encapsulation?
Encapsulation means restricting direct access to variables and using methods.
Example:
class Bank:
def __init__(self,balance):
self.__balance = balance
__balance becomes private.
Access through methods:
def get_balance(self):
return self.__balance
5️ What is Inheritance?
Inheritance allows a class to reuse properties of another class.
Example:
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
pass
d = Dog()
[Link]()
6️ What is Method Overriding?
Child class modifies the parent class method.
Example:
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def speak(self):
print("Bark")
7️ What is Polymorphism?
Same method works differently for different objects.
Example:
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
for animal in (Dog(),Cat()):
[Link]()
8️ What are @staticmethod and @classmethod?
Static Method
Does not depend on class or instance.
class Math:
@staticmethod
def add(a,b):
return a+b
Class Method
Works with the class itself.
class Person:
count = 0
@classmethod
def increment(cls):
[Link] += 1
9️ What is Abstraction?
Hiding complex implementation and showing only essential features.
Example using abstract class:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Child class must implement area().
10 What is Multiple Inheritance?
A class can inherit from multiple parent classes.
Example:
class A:
pass
class B:
pass
class C(A,B):
pass
Python resolves this using MRO (Method Resolution Order).
One very common follow-up question
Interviewers may ask:
“What is the difference between abstraction and encapsulation?”
Best answer:
Encapsulation Abstraction
Hides data Hides implementation
Achieved using access modifiers Achieved using abstract classes
One powerful tip for your interview
Since your background is .NET, you can say:
“OOP principles like inheritance, encapsulation, and polymorphism remain the same across
languages like C# and Python. The main difference is syntax and some implementation details.”
This shows strong engineering thinking.
For backend developers with ~6 years experience, interviewers at Tata Consultancy Services
often ask Python + SQL scenario questions.
These test whether you can build real backend systems, not just write scripts.
Below are 5 common scenarios with the kind of answers interviewers expect.
1️ Scenario: Fetching Large Data from Database
Question
Your Python application needs to fetch millions of records from SQL Server. Loading
everything into memory causes performance issues. How will you solve it?
Expected approach
Fetch data in batches
Use pagination
Use generators
Example:
[Link]("SELECT * FROM users")
while True:
rows = [Link](1000)
if not rows:
break
for row in rows:
process(row)
Why this works
Avoids loading entire dataset into memory.
2️ Scenario: Prevent SQL Injection
Question
Your Python API receives user input and queries the database. How will you prevent SQL
injection?
❌ Wrong approach
query = "SELECT * FROM users WHERE name = '" + name + "'"
✔ Correct approach (Parameterized query)
[Link](
"SELECT * FROM users WHERE name=%s",
(name,)
)
This ensures safe query execution.
3️ Scenario: Slow Database Query
Question
Your Python application is slow because database queries take too long. What steps will you
take?
Expected answer
1. Analyze query using execution plan
2. Add indexes
3. Optimize joins
4. Fetch only required columns
5. Use connection pooling
Example improvement:
SELECT id,name
FROM users
WHERE email = ?
Instead of:
SELECT *
FROM users
4️ Scenario: Handling Transactions
Question
You are inserting data into multiple tables using Python. If one insert fails, all changes should
rollback. How will you implement this?
Example:
try:
[Link]()
[Link]("INSERT INTO orders VALUES (...)")
[Link]("INSERT INTO payments VALUES (...)")
[Link]()
except:
[Link]()
This ensures data consistency.
5️ Scenario: API Returning Paginated Results
Question
Your API should return 100 records per request instead of the full dataset.
SQL query:
SELECT *
FROM employees
ORDER BY id
OFFSET 0 ROWS
FETCH NEXT 100 ROWS ONLY
Python example:
page_size = 100
offset = (page - 1) * page_size
query = """
SELECT *
FROM employees
ORDER BY id
OFFSET %s ROWS FETCH NEXT %s ROWS ONLY
"""
One advanced scenario they may ask
“How would you design a Python API that handles 10,000 database requests per second?”
Expected points:
Connection pooling
Async APIs
Caching (Redis)
Optimized SQL queries
Load balancing
One very important tip for your interview
Since your background includes SQL Server and PL/SQL, highlight this when answering:
Example line:
“In my previous projects I worked extensively with SQL Server stored procedures and query
optimization, which helped improve backend performance significantly.”
This will strengthen your backend developer profile.