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?
Feature | Python | Java | C++ |
---|---|---|---|
Typing | Dynamic | Static | Static |
Compilation | No (interpreted) | Yes | Yes |
Performance | Slower than C++ | Faster than Python | Fast |
Simplicity | High | Medium | Low |
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?
Feature | List | Tuple |
---|---|---|
Mutability | Mutable | Immutable |
Performance | Slower | Faster |
Syntax | [] | () |
Example:
my_list = [1, 2, 3] # Mutable
my_tuple = (1, 2, 3) # Immutable
5. What is the difference between is
and ==
in Python?
Operator | Checks | Example |
---|---|---|
== | Values | 5 == 5 (β
True) |
is | Memory location | x 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?
Method | Usage |
---|---|
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?
Method | Removes |
---|---|
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
?
Statement | Function |
---|---|
break | Exits loop immediately |
continue | Skips current iteration |
pass | Placeholder, 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
?
Parameter | Usage |
---|---|
*args | Passes multiple arguments as a tuple |
**kwargs | Passes 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 Type | Behavior |
---|---|
Shallow Copy | Copies references to objects (changes affect original) |
Deep Copy | Creates 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()
?
Function | Description |
---|---|
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
?
Keyword | Behavior |
---|---|
return | Exits function and returns a value |
yield | Returns 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
?
Decorator | Behavior |
---|---|
@staticmethod | Does not access instance/class variables |
@classmethod | Takes 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
?
Keyword | Usage |
---|---|
self | Refers 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 Type | Decorator | Accesses Instance (self )? | Accesses Class (cls )? |
---|---|---|---|
Instance Method | None | β 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()
?
Method | Purpose |
---|---|
del | Deletes 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()
?
Function | Purpose |
---|---|
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?
Method | Purpose |
---|---|
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()
?
Function | Description |
---|---|
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
?
Keyword | Scope |
---|---|
global | Modifies a global variable |
nonlocal | Modifies 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()
?
Function | Purpose |
---|---|
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 Type | Characteristics |
---|---|
List | Ordered, mutable, allows duplicates |
Tuple | Ordered, immutable, allows duplicates |
Set | Unordered, mutable, no duplicates |
Dictionary | Key-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?
Type | Can be Modified? | Examples |
---|---|---|
Mutable | β Yes | Lists, dictionaries, sets |
Immutable | β No | Tuples, 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()
?
Function | Behavior |
---|---|
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
?
Operator | Behavior |
---|---|
== | Compares values |
is | Compares 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
?
Statement | Behavior |
---|---|
break | Exits the loop |
continue | Skips current iteration |
pass | Does 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?
Type | Behavior |
---|---|
Shallow Copy | Copies references of nested objects (modifications affect both copies) |
Deep Copy | Recursively 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?
Feature | Iterator | Generator |
---|---|---|
Creation | Uses __iter__() & __next__() | Uses yield |
Memory | Uses more memory | Saves 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()
?
Function | Purpose |
---|---|
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()
?
Function | Purpose |
---|---|
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?
Parameter | Purpose |
---|---|
*args | Pass multiple positional arguments |
**kwargs | Pass 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?
Feature | Module | Package |
---|---|---|
Definition | Single Python file (.py ) | Collection of modules |
Example | math.py | Folder 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
?
Value | Meaning |
---|---|
None | Absence of value |
False | Boolean 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?
Feature | copy() (Shallow Copy) | deepcopy() (Deep Copy) |
---|---|---|
Nested Objects | References original objects | Creates new copies of nested objects |
Modification Effect | Changes in one affect the other | Independent 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()
?
Feature | set() | 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?
Feature | pop() | 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()
?
Feature | sorted() | .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 | @property | Getter/Setter Methods |
---|---|---|
Access | Acts as an attribute | Uses 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 Type | Examples | Can be modified? |
---|---|---|
Mutable | list , dict , set | β Yes |
Immutable | int , 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?
Operator | Checks |
---|---|
is | Identity (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! π―π
Β