TCS Python Interview Questions

Are you preparing for a TCS Python interview and looking for the most commonly asked questions? You’ve come to the right place! Python is a versatile and widely used programming language in software development, data science, and automation, making it a crucial skill for candidates applying to Tata Consultancy Services (TCS).

In this comprehensive guide, we’ve compiled the Top 100 TCS Python Interview Questions with Detailed Answers to help you crack your interview with confidence. Whether you are a fresher or an experienced developer, these questions will cover fundamental and advanced concepts, including OOPs, data structures, multithreading, exception handling, and Python libraries.

Read on to enhance your Python skills and boost your chances of securing your dream job at TCS! πŸš€


1. What are the key features of Python?

Python is a high-level, interpreted, object-oriented programming language. Its key features include:

βœ… Easy to Learn – Simple and readable syntax.
βœ… Interpreted Language – No need for compilation.
βœ… Dynamically Typed – No need to declare variable types.
βœ… Object-Oriented – Supports classes and objects.
βœ… Extensive Libraries – Rich standard libraries for various applications.
βœ… Cross-platform – Works on Windows, macOS, and Linux.


2. How is Python different from other programming languages?

FeaturePythonJavaC++
TypingDynamicStaticStatic
CompilationNo (interpreted)YesYes
PerformanceSlower than C++Faster than PythonFast
SimplicityHighMediumLow

Python is preferred for data science, AI, automation, and web development due to its simplicity.


3. What are Python’s data types?

Python has the following built-in data types:
πŸ”Ή Numeric – int, float, complex
πŸ”Ή Sequence – list, tuple, range
πŸ”Ή Text – str
πŸ”Ή Set types – set, frozenset
πŸ”Ή Mapping – dict
πŸ”Ή Boolean – bool

Example:

x = 10  # int
y = 10.5  # float
name = "TCS"  # str
items = [1, 2, 3]  # list
values = (4, 5, 6)  # tuple
unique = {1, 2, 3}  # set
info = {"name": "Alice", "age": 25}  # dict

4. What is the difference between a list and a tuple?

FeatureListTuple
MutabilityMutableImmutable
PerformanceSlowerFaster
Syntax[]()

Example:

my_list = [1, 2, 3]  # Mutable
my_tuple = (1, 2, 3)  # Immutable

5. What is the difference between is and == in Python?

OperatorChecksExample
==Values5 == 5 (βœ… True)
isMemory locationx is y (βœ… True only if same object)

Example:

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a == c)  # True (same values)
print(a is c)  # False (different objects)
print(a is b)  # True (same object)

6. What is Python’s slicing?

Slicing is used to extract a subset of elements from sequences.

Example:

s = "Python"
print(s[1:4])  # 'yth' (from index 1 to 3)
print(s[:3])  # 'Pyt' (first 3 characters)
print(s[-3:])  # 'hon' (last 3 characters)

7. What is the difference between append() and extend() in Python?

MethodUsage
append()Adds a single item to the list
extend()Merges another iterable into the list

Example:

lst = [1, 2, 3]
lst.append([4, 5])  # Appends a list
print(lst)  # [1, 2, 3, [4, 5]]

lst = [1, 2, 3]
lst.extend([4, 5])  # Extends with list elements
print(lst)  # [1, 2, 3, 4, 5]

8. What is the difference between pop() and remove() in lists?

MethodRemoves
pop()Item at an index (default last)
remove()First occurrence of a value

Example:

lst = [1, 2, 3, 4]
lst.pop(2)  # Removes index 2
print(lst)  # [1, 2, 4]

lst.remove(2)  # Removes value 2
print(lst)  # [1, 4]

9. How do you iterate over a dictionary in Python?

Example:

data = {"name": "Alice", "age": 25}

for key, value in data.items():
    print(key, "->", value)

βœ… Output:

name -> Alice  
age -> 25  

10. How do you handle exceptions in Python?

Example:

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

βœ… Output:

Cannot divide by zero!

11. What are Python’s looping constructs?

Python supports:
πŸ”Ή for loop – Iterates over sequences
πŸ”Ή while loop – Runs until a condition is false

Example:

for i in range(5):
    print(i)

βœ… Output:

0 1 2 3 4

12. What is the difference between break, continue, and pass?

StatementFunction
breakExits loop immediately
continueSkips current iteration
passPlaceholder, does nothing

Example:

for i in range(5):
    if i == 2:
        continue
    print(i)

βœ… Output:

0 1 3 4

13. What is recursion in Python?

A function calling itself until a base condition is met.

Example:

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # 120

14. What are Python’s *args and **kwargs?

ParameterUsage
*argsPasses multiple arguments as a tuple
**kwargsPasses key-value pairs as a dictionary

Example:

def greet(*names):
    for name in names:
        print("Hello", name)

greet("Alice", "Bob")  # Hello Alice, Hello Bob

15. What are Python’s built-in functions?

Some common built-in functions include:
πŸ”Ή len(), type(), print()
πŸ”Ή sorted(), max(), min()
πŸ”Ή sum(), map(), filter(), zip()

Β 


16. How do you reverse a string in Python?

Example:

s = "Python"
print(s[::-1])  # 'nohtyP'

17. What is the difference between deep copy and shallow copy?

Copy TypeBehavior
Shallow CopyCopies references to objects (changes affect original)
Deep CopyCreates a new copy (changes don’t affect original)

Example:

import copy

lst1 = [[1, 2], [3, 4]]
shallow = copy.copy(lst1)
deep = copy.deepcopy(lst1)

shallow[0][0] = 99
print(lst1)  # [[99, 2], [3, 4]]
deep[0][0] = 100
print(lst1)  # [[99, 2], [3, 4]]

18. How do you check if a key exists in a dictionary?

Example:

data = {"name": "Alice", "age": 25}
if "name" in data:
    print("Key exists!")

βœ… Output:

Key exists!

19. How do you merge two dictionaries in Python?

Example:

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

merged = {**dict1, **dict2}
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

20. What is a lambda function?

A lambda function is an anonymous function written in one line.

Example:

square = lambda x: x * x
print(square(5))  # 25

21. What is the difference between map(), filter(), and reduce()?

FunctionDescription
map()Applies a function to all items in an iterable
filter()Returns elements that satisfy a condition
reduce()Applies a function cumulatively

Example:

from functools import reduce

nums = [1, 2, 3, 4]
print(list(map(lambda x: x * 2, nums)))  # [2, 4, 6, 8]
print(list(filter(lambda x: x % 2 == 0, nums)))  # [2, 4]
print(reduce(lambda x, y: x + y, nums))  # 10

22. What is list comprehension?

List comprehension is a concise way to create lists.

Example:

squares = [x * x for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

23. How do you find the length of a list in Python?

Example:

lst = [1, 2, 3, 4]
print(len(lst))  # 4

24. What are Python generators?

A generator is a function that yields values lazily using yield.

Example:

def count():
    for i in range(5):
        yield i

gen = count()
print(next(gen))  # 0
print(next(gen))  # 1

25. What is the difference between yield and return?

KeywordBehavior
returnExits function and returns a value
yieldReturns value but function remembers state

Example:

def test():
    yield 1
    yield 2

gen = test()
print(next(gen))  # 1
print(next(gen))  # 2

26. What is the purpose of with statement in Python?

The with statement manages resources and automatically closes them.

Example:

with open("file.txt", "r") as file:
    content = file.read()

βœ… No need to manually close the file!


27. What is self in Python classes?

self refers to the current instance of a class.

Example:

class Person:
    def __init__(self, name):
        self.name = name

p = Person("Alice")
print(p.name)  # Alice

28. What is the difference between @staticmethod and @classmethod?

DecoratorBehavior
@staticmethodDoes not access instance/class variables
@classmethodTakes class (cls) as first argument

Example:

class MyClass:
    @staticmethod
    def static_method():
        print("Static method")

    @classmethod
    def class_method(cls):
        print("Class method")

MyClass.static_method()  # Static method
MyClass.class_method()  # Class method

29. What is multiple inheritance in Python?

Python supports multiple inheritance, allowing a class to inherit from multiple parent classes.

Example:

class A:
    def methodA(self):
        print("Class A")

class B:
    def methodB(self):
        print("Class B")

class C(A, B):
    pass

obj = C()
obj.methodA()  # Class A
obj.methodB()  # Class B

30. What is the difference between super() and self?

KeywordUsage
selfRefers to the instance of the current class
super()Calls methods of the parent class

Example:

class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        super().greet()
        print("Hello from Child")

c = Child()
c.greet()

βœ… Output:

Hello from Parent  
Hello from Child

Β 


31. What is the difference between instance, class, and static methods?

Method TypeDecoratorAccesses Instance (self)?Accesses Class (cls)?
Instance MethodNoneβœ… Yes❌ No
Class Method@classmethod❌ Noβœ… Yes
Static Method@staticmethod❌ No❌ No

Example:

class Example:
    def instance_method(self):
        return "Instance Method"

    @classmethod
    def class_method(cls):
        return "Class Method"

    @staticmethod
    def static_method():
        return "Static Method"

obj = Example()
print(obj.instance_method())  # Instance Method
print(Example.class_method())  # Class Method
print(Example.static_method())  # Static Method

32. What is the difference between del, remove(), and pop()?

MethodPurpose
delDeletes an object or an index from a list
remove()Removes a specific value from a list
pop()Removes and returns an element at a given index

Example:

lst = [1, 2, 3, 4]

del lst[1]  # Deletes index 1
print(lst)  # [1, 3, 4]

lst.remove(3)  # Removes value 3
print(lst)  # [1, 4]

print(lst.pop(0))  # 1 (removes & returns)
print(lst)  # [4]

33. What are Python’s built-in modules?

Some common built-in modules include:
βœ… math – Mathematical functions
βœ… random – Random number generation
βœ… datetime – Date and time functions
βœ… os – Interacting with the operating system
βœ… sys – System-specific parameters and functions
βœ… json – JSON serialization

Example:

import math
print(math.sqrt(25))  # 5.0

34. What is __init__ in Python?

The __init__ method is the constructor that initializes an object when it is created.

Example:

class Person:
    def __init__(self, name):
        self.name = name

p = Person("Alice")
print(p.name)  # Alice

35. What are Python’s special (dunder) methods?

Special methods (dunder methods) allow operator overloading and customization.
πŸ”Ή __init__() – Constructor
πŸ”Ή __str__() – String representation
πŸ”Ή __len__() – Length of an object
πŸ”Ή __add__() – Overloads + operator

Example:

class Box:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return Box(self.value + other.value)

b1 = Box(5)
b2 = Box(10)
b3 = b1 + b2
print(b3.value)  # 15

36. What is the difference between isinstance() and issubclass()?

FunctionPurpose
isinstance(obj, Class)Checks if an object belongs to a class
issubclass(ClassA, ClassB)Checks if ClassA is a subclass of ClassB

Example:

class A: pass
class B(A): pass

obj = B()
print(isinstance(obj, B))  # True
print(isinstance(obj, A))  # True
print(issubclass(B, A))  # True

37. What are Python’s string methods?

MethodPurpose
upper()Converts to uppercase
lower()Converts to lowercase
strip()Removes spaces
replace(a, b)Replaces a with b
split(delim)Splits a string by delimiter

Example:

s = " Hello Python "
print(s.strip().upper())  # "HELLO PYTHON"

38. How do you read and write files in Python?

Example:

# Writing to a file
with open("test.txt", "w") as file:
    file.write("Hello, World!")

# Reading from a file
with open("test.txt", "r") as file:
    print(file.read())  # Hello, World!

39. What is the difference between read(), readline(), and readlines()?

FunctionDescription
read()Reads entire file
readline()Reads one line
readlines()Reads all lines as a list

Example:

with open("test.txt", "r") as file:
    print(file.readline())  # Reads first line

40. How do you handle multiple exceptions in Python?

Example:

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid value!")

41. What is the difference between global and nonlocal?

KeywordScope
globalModifies a global variable
nonlocalModifies an enclosing function’s variable

Example:

x = 10

def outer():
    y = 5
    def inner():
        nonlocal y
        y += 1
    inner()
    print(y)  # 6

42. What is enumerate() in Python?

The enumerate() function adds an index to iterables.

Example:

items = ["a", "b", "c"]
for index, item in enumerate(items):
    print(index, item)

βœ… Output:

0 a  
1 b  
2 c  

43. What is the difference between zip() and enumerate()?

FunctionPurpose
zip()Combines two iterables
enumerate()Adds index to an iterable

Example:

a = [1, 2, 3]
b = ["x", "y", "z"]
print(list(zip(a, b)))  # [(1, 'x'), (2, 'y'), (3, 'z')]

44. What is the use of defaultdict in Python?

defaultdict is a dictionary that returns a default value for missing keys.

Example:

from collections import defaultdict

d = defaultdict(int)
print(d["missing"])  # 0 (default)

45. What is the purpose of Counter in Python?

Counter counts occurrences of elements in a list.

Example:

from collections import Counter

nums = [1, 2, 2, 3, 3, 3]
count = Counter(nums)
print(count)  # Counter({3: 3, 2: 2, 1: 1})

Β 


46. What is the difference between list, tuple, set, and dictionary?

Data TypeCharacteristics
ListOrdered, mutable, allows duplicates
TupleOrdered, immutable, allows duplicates
SetUnordered, mutable, no duplicates
DictionaryKey-value pairs, mutable, no duplicate keys

Example:

lst = [1, 2, 3]  
tup = (1, 2, 3)  
st = {1, 2, 3}  
dct = {"a": 1, "b": 2}  

47. What is the difference between mutable and immutable objects?

TypeCan be Modified?Examples
Mutableβœ… YesLists, dictionaries, sets
Immutable❌ NoTuples, strings, integers

Example:

# Mutable
lst = [1, 2, 3]
lst[0] = 99
print(lst)  # [99, 2, 3]

# Immutable
tup = (1, 2, 3)
# tup[0] = 99  # ❌ Error: Tuples are immutable

48. How do you remove duplicates from a list?

Example:

lst = [1, 2, 2, 3, 3, 4]
unique_list = list(set(lst))
print(unique_list)  # [1, 2, 3, 4]

49. How do you swap two variables in Python?

Example:

a, b = 5, 10
a, b = b, a
print(a, b)  # 10 5

50. What is the purpose of the join() method?

join() concatenates strings using a separator.

Example:

words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence)  # "Hello World"

51. How do you generate random numbers in Python?

Example:

import random
print(random.randint(1, 10))  # Random integer between 1 and 10

52. What is a Python decorator?

A decorator modifies functions or classes dynamically.

Example:

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

βœ… Output:

Before function call  
Hello!  
After function call  

53. How do you sort a list in Python?

Example:

nums = [4, 1, 3, 2]
nums.sort()
print(nums)  # [1, 2, 3, 4]

To sort without modifying the original list:

sorted_list = sorted(nums)
print(sorted_list)

54. How do you find the factorial of a number using recursion?

Example:

def factorial(n):
    return 1 if n == 0 else n * factorial(n - 1)

print(factorial(5))  # 120

55. How do you check if a string is a palindrome?

Example:

def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome("radar"))  # True
print(is_palindrome("hello"))  # False

56. What is exception handling in Python?

Exception handling prevents programs from crashing due to errors.

Example:

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

βœ… Output:

Cannot divide by zero!

57. How do you find the largest element in a list?

Example:

nums = [10, 20, 5, 8]
print(max(nums))  # 20

58. What is the difference between any() and all()?

FunctionBehavior
any()Returns True if at least one value is True
all()Returns True only if all values are True

Example:

print(any([False, False, True]))  # True
print(all([True, True, False]))  # False

59. What is the difference between == and is?

OperatorBehavior
==Compares values
isCompares memory addresses

Example:

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a == c)  # True (same values)
print(a is c)  # False (different objects)
print(a is b)  # True (same object)

60. What is the difference between break, continue, and pass?

StatementBehavior
breakExits the loop
continueSkips current iteration
passDoes nothing (used as a placeholder)

Example:

for i in range(5):
    if i == 2:
        continue  # Skips 2
    if i == 4:
        break  # Stops loop
    print(i)

# Output: 0 1 3

Β 


61. What is the difference between deep copy and shallow copy?

TypeBehavior
Shallow CopyCopies references of nested objects (modifications affect both copies)
Deep CopyRecursively copies all objects (modifications do not affect the original)

Example:

import copy

# Shallow Copy
list1 = [[1, 2], [3, 4]]
shallow = copy.copy(list1)
shallow[0][0] = 99
print(list1)  # [[99, 2], [3, 4]]

# Deep Copy
list2 = [[1, 2], [3, 4]]
deep = copy.deepcopy(list2)
deep[0][0] = 99
print(list2)  # [[1, 2], [3, 4]]

62. How does Python manage memory?

Python uses automatic memory management via:
βœ… Reference Counting – Tracks object references
βœ… Garbage Collection (GC) – Removes unused objects
βœ… Heap Memory Allocation – Stores objects dynamically

Example:

import sys

x = [1, 2, 3]
print(sys.getrefcount(x))  # Reference count of x

63. What are Python iterators and generators?

FeatureIteratorGenerator
CreationUses __iter__() & __next__()Uses yield
MemoryUses more memorySaves memory (lazy evaluation)

Example: Iterator:

class MyIterator:
    def __init__(self, max):
        self.max = max
        self.n = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.n < self.max:
            self.n += 1
            return self.n
        else:
            raise StopIteration

it = MyIterator(3)
print(next(it))  # 1
print(next(it))  # 2

Example: Generator:

def my_generator():
    for i in range(3):
        yield i

gen = my_generator()
print(next(gen))  # 0
print(next(gen))  # 1

64. What is the difference between map(), filter(), and reduce()?

FunctionPurpose
map()Applies a function to all items in an iterable
filter()Filters elements based on a condition
reduce()Reduces an iterable to a single value

Example:

from functools import reduce

nums = [1, 2, 3, 4]

print(list(map(lambda x: x * 2, nums)))  # [2, 4, 6, 8]
print(list(filter(lambda x: x % 2 == 0, nums)))  # [2, 4]
print(reduce(lambda x, y: x + y, nums))  # 10

65. What is Python’s with statement?

The with statement simplifies file handling by automatically closing resources.

Example:

with open("file.txt", "w") as file:
    file.write("Hello, World!")  # No need to close manually

66. How do you merge two dictionaries in Python?

Example:

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

# Method 1: Using update()
dict1.update(dict2)
print(dict1)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Method 2: Using dictionary unpacking (Python 3.5+)
merged = {**dict1, **dict2}
print(merged)

67. What is the difference between type() and isinstance()?

FunctionPurpose
type(obj)Returns object’s type
isinstance(obj, Class)Checks if obj is an instance of Class

Example:

print(type(10))  # <class 'int'>
print(isinstance(10, int))  # True

68. What is the difference between @staticmethod and @classmethod?

Feature@staticmethod@classmethod
Takes self?❌ No❌ No
Takes cls?❌ Noβœ… Yes
Works on instances?βœ… Yesβœ… Yes
Works on class?βœ… Yesβœ… Yes

Example:

class Example:
    @staticmethod
    def static_method():
        return "Static Method"

    @classmethod
    def class_method(cls):
        return "Class Method"

print(Example.static_method())  # Static Method
print(Example.class_method())  # Class Method

69. What are args and kwargs in Python?

ParameterPurpose
*argsPass multiple positional arguments
**kwargsPass multiple keyword arguments

Example:

def my_function(*args, **kwargs):
    print(args)
    print(kwargs)

my_function(1, 2, 3, name="Alice", age=25)

βœ… Output:

(1, 2, 3)  
{'name': 'Alice', 'age': 25}

70. What is the difference between a module and a package?

FeatureModulePackage
DefinitionSingle Python file (.py)Collection of modules
Examplemath.pyFolder with __init__.py

71. How do you check if a file exists in Python?

Example:

import os

print(os.path.exists("file.txt"))  # True or False

72. How do you reverse a string in Python?

Example:

s = "Python"
print(s[::-1])  # "nohtyP"

73. What is the difference between None and False?

ValueMeaning
NoneAbsence of value
FalseBoolean False

Example:

x = None
y = False
print(bool(x))  # False
print(bool(y))  # False

74. What are f-strings in Python?

F-strings (`f”{}“) provide formatted string literals.

Example:

name = "Alice"
print(f"Hello, {name}!")  # Hello, Alice!

75. How do you implement a stack in Python?

Example:

stack = []
stack.append(1)  # Push
stack.append(2)
print(stack.pop())  # 2 (Pop)

Β 


76. How do you implement a queue in Python?

Python provides multiple ways to implement a queue:

Using collections.deque (Recommended for efficiency)

from collections import deque

queue = deque()
queue.append(1)  # Enqueue
queue.append(2)
print(queue.popleft())  # 1 (Dequeue)

Using queue.Queue (Thread-safe approach)

from queue import Queue

q = Queue()
q.put(1)
q.put(2)
print(q.get())  # 1

77. What is the difference between deepcopy() and copy() in Python?

Featurecopy() (Shallow Copy)deepcopy() (Deep Copy)
Nested ObjectsReferences original objectsCreates new copies of nested objects
Modification EffectChanges in one affect the otherIndependent copies

Example:

import copy

lst1 = [[1, 2], [3, 4]]
shallow = copy.copy(lst1)
deep = copy.deepcopy(lst1)

shallow[0][0] = 99
print(lst1)  # [[99, 2], [3, 4]] (Shallow copy affected)

deep[0][0] = 42
print(lst1)  # [[99, 2], [3, 4]] (Deep copy unaffected)

78. What is the purpose of the zip() function?

zip() combines multiple iterables into tuples.

Example:

names = ["Alice", "Bob"]
ages = [25, 30]

zipped = list(zip(names, ages))
print(zipped)  # [('Alice', 25), ('Bob', 30)]

79. How do you convert a list to a dictionary in Python?

Example:

keys = ["name", "age"]
values = ["Alice", 25]

dictionary = dict(zip(keys, values))
print(dictionary)  # {'name': 'Alice', 'age': 25}

80. What is the difference between set() and frozenset()?

Featureset()frozenset()
Mutable?βœ… Yes❌ No
Supports Modification?βœ… Yes (add, remove)❌ No

Example:

s = set([1, 2, 3])
s.add(4)

fs = frozenset([1, 2, 3])
# fs.add(4)  # ❌ Error: frozenset is immutable

81. How do you remove whitespaces from a string?

Example:

s = "  Hello World  "
print(s.strip())  # "Hello World"
print(s.lstrip())  # "Hello World  "
print(s.rstrip())  # "  Hello World"

82. What is a lambda function in Python?

A lambda function is an anonymous function.

Example:

add = lambda x, y: x + y
print(add(2, 3))  # 5

83. How do you remove an element from a list?

Example:

lst = [1, 2, 3, 4]

lst.remove(2)  # Removes first occurrence of 2
print(lst)  # [1, 3, 4]

del lst[1]  # Removes element at index 1
print(lst)  # [1, 4]

84. How do you count the frequency of elements in a list?

Example:

from collections import Counter

lst = [1, 2, 2, 3, 3, 3]
count = Counter(lst)
print(count)  # {1: 1, 2: 2, 3: 3}

85. What is the difference between pop() and del in Python?

Featurepop()del
Returns removed element?βœ… Yes❌ No
Can delete a variable?❌ Noβœ… Yes

Example:

lst = [1, 2, 3]

print(lst.pop(1))  # 2 (Removes and returns element at index 1)
del lst[0]  # Removes element at index 0
print(lst)  # [3]

86. What is the difference between sorted() and .sort()?

Featuresorted().sort()
Returns new list?βœ… Yes❌ No (Modifies original list)

Example:

lst = [3, 1, 2]

print(sorted(lst))  # [1, 2, 3] (Original list remains unchanged)
lst.sort()
print(lst)  # [1, 2, 3] (Original list modified)

87. What is the purpose of enumerate() in Python?

enumerate() adds an index to an iterable.

Example:

names = ["Alice", "Bob"]
for index, name in enumerate(names, start=1):
    print(index, name)

# Output:
# 1 Alice
# 2 Bob

88. What is itertools in Python?

itertools provides efficient looping utilities.

Example:

from itertools import permutations

print(list(permutations([1, 2, 3])))  
# [(1,2,3), (1,3,2), (2,1,3), ...]

89. What is the difference between @property and getter/setter methods?

Feature@propertyGetter/Setter Methods
AccessActs as an attributeUses get_ and set_ methods

Example:

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

p = Person("Alice")
print(p.name)  # Alice (Accesses like an attribute)

90. What is the purpose of glob module?

The glob module finds files matching a pattern.

Example:

import glob

print(glob.glob("*.txt"))  # Lists all `.txt` files in the directory

Β 

Β 

Here are the next 10 TCS Python interview questions with detailed answers and examples:


91. What is the difference between mutable and immutable objects in Python?

Object TypeExamplesCan be modified?
Mutablelist, dict, setβœ… Yes
Immutableint, float, str, tuple❌ No

Example:

# Mutable (Lists)
lst = [1, 2, 3]
lst[0] = 99
print(lst)  # [99, 2, 3]

# Immutable (Strings)
s = "hello"
s = s.replace("h", "H")  # Creates a new string
print(s)  # "Hello"

92. How can you handle exceptions in Python?

Use try-except blocks to handle errors.

Example:

try:
    x = 10 / 0  # Division by zero
except ZeroDivisionError:
    print("Cannot divide by zero!")

βœ… Output:

Cannot divide by zero!

93. What is a docstring in Python?

A docstring is a multi-line string at the beginning of a function/class/module for documentation.

Example:

def add(a, b):
    """This function adds two numbers."""
    return a + b

print(add.__doc__)

βœ… Output:

This function adds two numbers.

94. What is the purpose of __name__ == "__main__" in Python?

This ensures that a script runs only when executed directly, not when imported as a module.

Example:

def main():
    print("Executed when run directly!")

if __name__ == "__main__":
    main()

βœ… Output (when run directly):

Executed when run directly!

βœ… Output (when imported in another script):
(No output)


95. How do you merge multiple lists in Python?

Example:

list1 = [1, 2]
list2 = [3, 4]

# Method 1: Using `+`
print(list1 + list2)  # [1, 2, 3, 4]

# Method 2: Using `extend()`
list1.extend(list2)
print(list1)  # [1, 2, 3, 4]

# Method 3: Using `*` (Python 3.6+)
merged = [*list1, *list2]
print(merged)  # [1, 2, 3, 4]

96. How do you swap two variables in Python without a temporary variable?

Example:

a, b = 5, 10
a, b = b, a
print(a, b)  # 10, 5

97. What is the difference between is and == in Python?

OperatorChecks
isIdentity (Memory location)
==Value (Equality)

Example:

x = [1, 2]
y = [1, 2]
z = x

print(x == y)  # True (Same values)
print(x is y)  # False (Different memory locations)
print(x is z)  # True (Same object)

98. How do you create a class in Python?

Example:

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, {self.name}!"

p = Person("Alice")
print(p.greet())  # Hello, Alice!

99. What is a decorator in Python?

A decorator modifies a function’s behavior.

Example:

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

βœ… Output:

Before function call
Hello!
After function call

100. What is multithreading in Python?

Multithreading allows multiple tasks to run concurrently.

Example:

import threading

def print_numbers():
    for i in range(5):
        print(i)

t1 = threading.Thread(target=print_numbers)
t1.start()
t1.join()

βœ… Output:

0
1
2
3
4

Β 

Β 

Mastering these Top 100 TCS Python Interview Questions will give you a strong foundation for your upcoming TCS technical interview. Python is a high-demand skill in the industry, and being well-prepared with real-world examples and in-depth explanations will set you apart from the competition.

Stay ahead by practicing coding challenges, working on Python projects, and revising key concepts regularly. If you found this guide helpful, share it with your peers and bookmark it for quick revision.

πŸ’‘ Looking for more Python interview tips? Keep following our blog for the latest Python interview trends, coding challenges, and expert guidance.

Good luck with your TCS Python interviewβ€”you’ve got this! πŸŽ―πŸš€

Β 

Leave a Reply

Your email address will not be published. Required fields are marked *