Capgemini Python Interview Questions
Python is one of the most popular programming languages, widely used for web development, data science, artificial intelligence, and automation. If you’re preparing for a Capgemini Python interview, mastering commonly asked questions can give you an edge over other candidates.
In this post, we have compiled the Top 100 Capgemini Python Interview Questions with detailed answers and examples. These questions cover basic to advanced concepts, including OOP, data structures, algorithms, frameworks, and best practices. Whether you’re a fresher or an experienced developer, these questions will help you crack your Python interview with confidence.
1. What are the key features of Python?
Python is a powerful, high-level, and easy-to-learn programming language. Some of its key features are:
✅ Simple and Easy to Learn – Python syntax is beginner-friendly.
✅ Interpreted Language – No need to compile; executes line by line.
✅ Dynamically Typed – No need to declare variable types explicitly.
✅ Object-Oriented & Functional Programming – Supports multiple paradigms.
✅ Large Standard Library – Rich set of built-in functions and modules.
Example:
print("Hello, World!") # Simple Python syntax
2. What is the difference between list
, tuple
, set
, and dictionary
in Python?
Data Type | Ordered? | Mutable? | Duplicates Allowed? | Example |
---|---|---|---|---|
list | ✅ Yes | ✅ Yes | ✅ Yes | [1, 2, 3, 4] |
tuple | ✅ Yes | ❌ No | ✅ Yes | (1, 2, 3, 4) |
set | ❌ No | ✅ Yes | ❌ No | {1, 2, 3, 4} |
dict | ✅ Yes (Python 3.7+) | ✅ Yes | Keys: ❌ No, Values: ✅ Yes | {'a': 1, 'b': 2} |
Example:
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_set = {1, 2, 3}
my_dict = {'a': 1, 'b': 2}
3. What is the difference between is
and ==
in Python?
Operator | Checks | Example | Output |
---|---|---|---|
is | Object identity (same memory location) | a is b | False (unless same object) |
== | Value equality | a == b | True (if values are same) |
Example:
a = [1, 2, 3]
b = a # Same memory location
c = [1, 2, 3] # Different memory location
print(a == c) # True (same values)
print(a is c) # False (different objects)
print(a is b) # True (same reference)
4. What are Python’s mutable and immutable data types?
✅ Mutable (Can be changed after creation):
list
,set
,dict
✅ Immutable (Cannot be changed after creation):
int
,float
,str
,tuple
,frozenset
Example:
# Mutable
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # [1, 2, 3, 4]
# Immutable
my_tuple = (1, 2, 3)
my_tuple[0] = 10 # ❌ TypeError: 'tuple' object does not support item assignment
5. What is the difference between deep copy and shallow copy?
Copy Type | Copies Nested Objects? | Example |
---|---|---|
Shallow Copy | ❌ No (references nested objects) | copy.copy(obj) |
Deep Copy | ✅ Yes (creates a new object for nested structures) | copy.deepcopy(obj) |
Example:
import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0][0] = 99
print(original) # [[99, 2, 3], [4, 5, 6]] (shallow copy affected)
print(deep) # [[1, 2, 3], [4, 5, 6]] (deep copy remains unchanged)
6. What is the difference between *args
and **kwargs
?
Operator | Used For | Example |
---|---|---|
*args | Passing multiple positional arguments | func(1, 2, 3) |
**kwargs | Passing multiple keyword arguments | func(name="Alice", age=25) |
Example:
def demo_func(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
demo_func(1, 2, 3, name="Alice", age=25)
Output:
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 25}
7. What is list comprehension in Python?
List comprehension is a concise way to create lists using a single line of code.
Example:
# Traditional way
squares = []
for i in range(5):
squares.append(i**2)
# Using list comprehension
squares = [i**2 for i in range(5)]
print(squares) # [0, 1, 4, 9, 16]
8. How does exception handling work in Python?
Python uses try-except-finally
blocks to handle exceptions.
Example:
try:
x = 1 / 0 # This will cause ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution complete.")
Output:
Cannot divide by zero!
Execution complete.
9. What is the difference between staticmethod
and classmethod
?
Method Type | Can Access Instance (self )? | Can Access Class (cls )? |
---|---|---|
@staticmethod | ❌ No | ❌ No |
@classmethod | ❌ No | ✅ Yes |
Example:
class Example:
@staticmethod
def static_method():
print("Static method called!")
@classmethod
def class_method(cls):
print("Class method called!")
Example.static_method() # ✅ Works without an instance
Example.class_method() # ✅ Works with class reference
10. What is the difference between lambda
and regular functions?
Function Type | Syntax | Supports Multiple Statements? |
---|---|---|
Regular Function | def func(): return x+y | ✅ Yes |
lambda Function | lambda x, y: x + y | ❌ No |
Example:
# Regular function
def add(a, b):
return a + b
# Lambda function
add_lambda = lambda a, b: a + b
print(add(3, 4)) # 7
print(add_lambda(3, 4)) # 7
11. What is the difference between del
, remove()
, and pop()
in Python?
Method | Use Case | Returns Value? | Affects Index? |
---|---|---|---|
del | Deletes item by index or entire variable | ❌ No | ✅ Yes |
remove() | Removes item by value | ❌ No | ✅ Yes |
pop() | Removes item by index (default last) | ✅ Yes | ✅ Yes |
Example:
my_list = [10, 20, 30, 40]
del my_list[1] # Deletes item at index 1
print(my_list) # [10, 30, 40]
my_list.remove(30) # Removes value 30
print(my_list) # [10, 40]
popped_value = my_list.pop() # Removes last element
print(popped_value) # 40
print(my_list) # [10]
12. What is the difference between deepcopy()
and assignment (=
) in Python?
Operation | Creates New Object? | Copies Nested Objects? |
---|---|---|
= (Assignment) | ❌ No (Creates reference) | ❌ No |
copy.deepcopy() | ✅ Yes (Creates new object) | ✅ Yes |
Example:
import copy
a = [[1, 2], [3, 4]]
b = a # Reference copy
c = copy.deepcopy(a) # Deep copy
a[0][0] = 99
print(b) # [[99, 2], [3, 4]] (Reference affected)
print(c) # [[1, 2], [3, 4]] (Deep copy unaffected)
13. What is the difference between isinstance()
and type()
in Python?
Function | Checks | Supports Inheritance? |
---|---|---|
isinstance(obj, Class) | Checks if an object is an instance of a class | ✅ Yes |
type(obj) is Class | Checks exact type | ❌ No |
Example:
class Animal: pass
class Dog(Animal): pass
d = Dog()
print(isinstance(d, Dog)) # True
print(isinstance(d, Animal)) # True (Inheritance)
print(type(d) is Dog) # True
print(type(d) is Animal) # False (type() doesn’t check inheritance)
14. What is a Python generator and how does it work?
A generator is a function that returns an iterator using yield
. Unlike regular functions, it does not store all values in memory.
Example:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
gen = count_up_to(3)
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3
15. How does Python’s memory management work?
Python uses automatic memory management, which includes:
✅ Reference Counting – Each object has a reference count.
✅ Garbage Collection (GC) – Removes unreferenced objects.
✅ Memory Pools – Uses memory blocks for efficiency.
Example:
import sys
x = [1, 2, 3]
print(sys.getrefcount(x)) # Shows reference count
16. What is the difference between global
, nonlocal
, and local variables?
Scope | Defined In | Can Be Modified? | Keyword |
---|---|---|---|
Local | Inside function | ✅ Yes | None |
Nonlocal | Inside nested function | ✅ Yes | nonlocal |
Global | Outside function | ✅ Yes | global |
Example:
x = "global"
def outer():
y = "outer"
def inner():
nonlocal y
global x
y = "modified outer"
x = "modified global"
inner()
print(y) # "modified outer"
outer()
print(x) # "modified global"
17. What are Python’s built-in data structures?
✅ List – Ordered, mutable, allows duplicates ([1, 2, 3]
)
✅ Tuple – Ordered, immutable ((1, 2, 3)
)
✅ Set – Unordered, no duplicates ({1, 2, 3}
)
✅ Dictionary – Key-value pairs ({"a": 1, "b": 2}
)
Example:
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Alice
18. What is the difference between break
, continue
, and pass
in Python?
Statement | Functionality |
---|---|
break | Exits loop immediately |
continue | Skips current iteration and moves to next |
pass | Does nothing, acts as a placeholder |
Example:
for i in range(5):
if i == 2:
break # Exits loop when i == 2
print(i)
for i in range(5):
if i == 2:
continue # Skips when i == 2
print(i)
def dummy_function():
pass # Placeholder for future code
19. What are Python’s built-in functions for file handling?
Function | Description |
---|---|
open() | Opens a file |
read() | Reads file contents |
write() | Writes to file |
close() | Closes file |
Example:
# Writing to a file
with open("sample.txt", "w") as file:
file.write("Hello, Python!")
# Reading from a file
with open("sample.txt", "r") as file:
content = file.read()
print(content) # Hello, Python!
20. What is the difference between map()
, filter()
, and reduce()
in Python?
Function | Purpose | Returns |
---|---|---|
map() | Applies function to all items | New list |
filter() | Filters elements based on condition | New list |
reduce() | Reduces list to single value | Single value |
Example:
from functools import reduce
nums = [1, 2, 3, 4, 5]
# map
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16, 25]
# filter
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
# reduce
sum_all = reduce(lambda x, y: x + y, nums)
print(sum_all) # 15
Here are the next 10 Capgemini Python interview questions with detailed answers and examples:
21. What is the difference between @staticmethod
, @classmethod
, and instance methods?
Method Type | Requires self ? | Requires cls ? | Can Access Instance Variables? | Can Access Class Variables? |
---|---|---|---|---|
Instance Method | ✅ Yes | ❌ No | ✅ Yes | ✅ Yes |
Class Method | ❌ No | ✅ Yes | ❌ No | ✅ Yes |
Static Method | ❌ No | ❌ No | ❌ No | ❌ No |
Example:
class Example:
class_var = "Class Variable"
def instance_method(self):
return f"Instance Method: {self.class_var}"
@classmethod
def class_method(cls):
return f"Class Method: {cls.class_var}"
@staticmethod
def static_method():
return "Static Method: No access to class or instance variables"
obj = Example()
print(obj.instance_method()) # ✅ Can access instance variables
print(Example.class_method()) # ✅ Can access class variables
print(Example.static_method()) # ❌ Cannot access class or instance variables
22. What is self
in Python?
self
represents the instance of a class.- It allows access to instance attributes and methods.
Example:
class Person:
def __init__(self, name):
self.name = name # Assign instance variable
def greet(self):
return f"Hello, my name is {self.name}!"
p = Person("Alice")
print(p.greet()) # Hello, my name is Alice!
23. What is the difference between Python 2 and Python 3?
Feature | Python 2 | Python 3 |
---|---|---|
Print Statement | print "Hello" | print("Hello") |
Integer Division | 5 / 2 = 2 | 5 / 2 = 2.5 |
Unicode Support | ASCII by default | Unicode by default |
Iterators | range() returns list | range() returns iterator |
24. What is the difference between ==
and is
in Python?
Operator | Checks | Example | Output |
---|---|---|---|
== | Compares values | a == b | ✅ True |
is | Compares object identity (memory location) | a is b | ❌ False |
Example:
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # ✅ True (Same values)
print(a is b) # ❌ False (Different objects)
print(a is c) # ✅ True (Same reference)
25. What is the difference between read()
, readline()
, and readlines()
?
Method | Reads | Returns |
---|---|---|
read(size) | Whole file or size bytes | String |
readline() | Single line | String |
readlines() | All lines | List of strings |
Example:
with open("example.txt", "r") as file:
print(file.read()) # Reads entire file
print(file.readline()) # Reads one line
print(file.readlines()) # Reads all lines as a list
26. What is a metaclass in Python?
A metaclass is a class of a class. It defines how a class behaves.
Example:
class Meta(type):
def __new__(cls, name, bases, dct):
dct['custom_attr'] = "Added by metaclass"
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
obj = MyClass()
print(obj.custom_attr) # Added by metaclass
27. What are Python’s built-in modules?
Some common built-in modules:
✅ os
– File system operations
✅ sys
– System-specific functions
✅ math
– Mathematical functions
✅ random
– Random number generation
✅ datetime
– Date and time handling
✅ re
– Regular expressions
Example:
import math
print(math.sqrt(16)) # 4.0
28. What is the with
statement in Python?
The with
statement ensures proper resource management (e.g., automatically closing files).
Example:
with open("file.txt", "w") as file:
file.write("Hello, world!") # No need to manually close()
29. What is monkey patching in Python?
Monkey patching allows dynamically modifying a module or class at runtime.
Example:
class Dog:
def bark(self):
return "Woof!"
# Monkey patching
def new_bark(self):
return "Meow!" # Changing bark to meow
Dog.bark = new_bark # Replacing method
dog = Dog()
print(dog.bark()) # Meow!
30. What is the zip()
function in Python?
The zip()
function combines multiple iterables into tuples.
Example:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
zipped = list(zip(names, ages))
print(zipped) # [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
31. What is the purpose of the enumerate()
function in Python?
enumerate()
adds an index to an iterable and returns a tuple containing the index and value.
Example:
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
✅ Output:
0 red
1 green
2 blue
32. How does exception handling work in Python?
Keyword | Purpose |
---|---|
try | Defines a block of code to test for errors |
except | Catches and handles exceptions |
else | Executes if no exceptions occur |
finally | Always executes, regardless of exceptions |
Example:
try:
x = 10 / 0 # Division by zero
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("No errors occurred.")
finally:
print("Execution finished.")
✅ Output:
Cannot divide by zero!
Execution finished.
33. What are Python magic methods?
Magic methods (also called dunder methods) are special methods with double underscores (__
) that allow operator overloading.
Example (__str__
and __add__
):
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Person: {self.name}"
def __add__(self, other):
return self.name + " & " + other.name
p1 = Person("Alice")
p2 = Person("Bob")
print(p1) # Calls __str__()
print(p1 + p2) # Calls __add__()
✅ Output:
Person: Alice
Alice & Bob
34. What is the difference between join()
and split()
methods?
Method | Purpose | Example |
---|---|---|
split() | Converts a string into a list | "a,b,c".split(",") → ['a', 'b', 'c'] |
join() | Converts a list into a string | " ".join(['a', 'b', 'c']) → "a b c" |
Example:
text = "Python is fun"
words = text.split() # ['Python', 'is', 'fun']
new_text = "-".join(words) # "Python-is-fun"
print(new_text)
35. What is a lambda function in Python?
A lambda function is an anonymous function (without a name) defined using the lambda
keyword.
Example:
add = lambda x, y: x + y
print(add(3, 5)) # 8
✅ Equivalent to:
def add(x, y):
return x + y
36. What is the difference between any()
and all()
in Python?
Function | Returns True if… | Example |
---|---|---|
any() | At least one element is True | any([0, 1, 0]) → True |
all() | All elements are True | all([1, 2, 3]) → True |
Example:
nums = [0, 1, 0]
print(any(nums)) # True (At least one non-zero)
print(all(nums)) # False (Not all are non-zero)
37. What is Python’s Counter
class used for?
The Counter
class (from collections
module) counts occurrences of elements in an iterable.
Example:
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
count = Counter(nums)
print(count) # Counter({3: 3, 2: 2, 1: 1})
38. What is a Python namedtuple
?
A namedtuple
is a lightweight, immutable alternative to a class that provides named fields.
Example:
from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
p = Person("Alice", 30)
print(p.name) # Alice
print(p.age) # 30
39. What is the @property
decorator in Python?
The @property
decorator makes a method act like an attribute.
Example:
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return (self._celsius * 9/5) + 32
temp = Temperature(25)
print(temp.fahrenheit) # 77.0 (No need to call as a method)
40. What is the defaultdict
in Python?
A defaultdict
provides a default value for missing keys.
Example:
from collections import defaultdict
dd = defaultdict(int)
dd["a"] += 1 # No KeyError
print(dd["a"]) # 1
print(dd["b"]) # 0 (default value)
41. What is the difference between deep copy and shallow copy in Python?
- Shallow Copy (
copy.copy()
): Creates a new object but references nested objects. - Deep Copy (
copy.deepcopy()
): Creates a new object and recursively copies all objects.
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
print(shallow) # [[99, 2], [3, 4]] (Shallow copy affected)
print(deep) # [[1, 2], [3, 4]] (Deep copy unaffected)
42. What is Python’s __init__
method?
__init__
is a constructor that initializes an object when a class is instantiated.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
c = Car("Tesla", "Model S")
print(c.brand, c.model) # Tesla Model S
43. What is the difference between mutable and immutable types in Python?
Type | Mutable? | Example |
---|---|---|
Mutable | ✅ Yes | list, dict, set |
Immutable | ❌ No | int, str, tuple |
Example:
# Mutable
lst = [1, 2, 3]
lst[0] = 99 # Allowed
# Immutable
tup = (1, 2, 3)
# tup[0] = 99 # ❌ Error (Cannot modify tuples)
44. How do you handle memory management in Python?
✅ Python has automatic memory management via Garbage Collection (GC) and Reference Counting.
Garbage Collection Example:
import gc
class Test:
def __del__(self):
print("Object deleted")
obj = Test()
del obj # Triggers garbage collection
gc.collect() # Manually trigger garbage collection
45. What is the difference between isinstance()
and type()
?
Function | Purpose | Example |
---|---|---|
isinstance(obj, Class) | Checks if obj is an instance of Class or subclass | isinstance(5, int) → ✅ True |
type(obj) | Returns the exact class of obj | type(5) == int → ✅ True |
Example:
class A: pass
class B(A): pass
obj = B()
print(isinstance(obj, A)) # ✅ True (Subclass check)
print(type(obj) == A) # ❌ False (Exact type doesn't match)
46. What is the map()
function in Python?
map()
applies a function to all elements in an iterable.
Example:
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared) # [1, 4, 9, 16]
47. What is the filter()
function in Python?
filter()
selects elements based on a condition.
Example:
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
48. What is the reduce()
function in Python?
reduce()
performs cumulative operations on an iterable.
Example:
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # 24
49. What is a Python generator?
- Generators use
yield
instead ofreturn
, allowing lazy evaluation.
Example:
def count():
yield 1
yield 2
yield 3
gen = count()
print(next(gen)) # 1
print(next(gen)) # 2
50. What is the difference between a generator and an iterator?
Feature | Generator | Iterator |
---|---|---|
Defined using | yield | __iter__() and __next__() |
Memory Usage | Efficient | May require more memory |
Example | def gen(): yield 1 | class Iter: def __iter__() |
Example:
# Generator
def gen():
yield 1
yield 2
g = gen()
print(next(g)) # 1
print(next(g)) # 2
51. What is the difference between sort()
and sorted()
?
Function | Mutability | Returns |
---|---|---|
sort() | Modifies list | None |
sorted() | Returns new sorted list | New list |
Example:
nums = [3, 1, 2]
# sorted() returns a new list
new_nums = sorted(nums)
print(new_nums) # [1, 2, 3]
# sort() modifies the list in place
nums.sort()
print(nums) # [1, 2, 3]
52. What is list comprehension in Python?
- A concise way to create lists.
Example:
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
53. What is dictionary comprehension in Python?
- A concise way to create dictionaries.
Example:
squares = {x: x ** 2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
54. How do you swap two variables in Python?
- Python allows swapping without a temp variable.
Example:
a, b = 5, 10
a, b = b, a
print(a, b) # 10, 5
55. What is the difference between del
, remove()
, and pop()
?
Method | Removes | Example |
---|---|---|
del | By index | del lst[1] |
remove() | By value | lst.remove(3) |
pop() | By index & returns value | lst.pop(1) |
Example:
nums = [10, 20, 30]
del nums[1] # Removes 20
nums.remove(30) # Removes 30
nums.pop(0) # Removes & returns 10
56. What is the difference between break
, continue
, and pass
in Python?
Statement | Purpose |
---|---|
break | Exits the loop entirely |
continue | Skips the current iteration and moves to the next |
pass | Acts as a placeholder, does nothing |
Example:
for i in range(5):
if i == 2:
break # Stops loop at 2
print(i)
for i in range(5):
if i == 2:
continue # Skips 2
print(i)
for i in range(5):
if i == 2:
pass # Does nothing
print(i)
✅ Output:
0
1
0
1
3
4
0
1
2
3
4
57. What is the difference between @staticmethod
and @classmethod
in Python?
Decorator | Purpose | First Argument |
---|---|---|
@staticmethod | No access to class or instance variables | None |
@classmethod | Works with class variables, not instance variables | cls (class reference) |
Example:
class Demo:
class_var = "Hello"
@staticmethod
def static_method():
print("Static Method")
@classmethod
def class_method(cls):
print("Class Method:", cls.class_var)
Demo.static_method() # Static Method
Demo.class_method() # Class Method: Hello
58. What are Python’s special methods (__repr__
vs __str__
)?
Method | Purpose |
---|---|
__repr__ | Official string representation (used for debugging) |
__str__ | Human-readable string representation |
Example:
class Person:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Person('{self.name}')"
def __str__(self):
return self.name
p = Person("Alice")
print(repr(p)) # Person('Alice')
print(str(p)) # Alice
59. What are Python’s set
methods?
Method | Purpose |
---|---|
union() | Combines sets |
intersection() | Common elements |
difference() | Elements in one set but not in another |
Example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.union(set2)) # {1, 2, 3, 4}
print(set1.intersection(set2)) # {2, 3}
print(set1.difference(set2)) # {1}
60. What is the difference between is
and ==
in Python?
Operator | Compares |
---|---|
== | Values |
is | Memory addresses |
Example:
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (Same values)
print(a is b) # False (Different objects)
print(a is c) # True (Same object)
61. What is duck typing in Python?
- If it behaves like a duck, it is a duck!
- Python doesn’t check types, only behavior.
Example:
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I'm quacking like a duck!")
def make_quack(thing):
thing.quack() # Works as long as 'quack()' exists
make_quack(Duck()) # Quack!
make_quack(Person()) # I'm quacking like a duck!
62. How does Python implement multi-threading?
- Python’s Global Interpreter Lock (GIL) limits true parallel execution.
- Use multiprocessing for CPU-bound tasks.
- Use threading for I/O-bound tasks.
Example:
import threading
def print_numbers():
for i in range(5):
print(i)
t = threading.Thread(target=print_numbers)
t.start()
t.join()
63. What is a metaclass in Python?
- A metaclass controls the creation of classes.
Example:
class Meta(type):
def __new__(cls, name, bases, dct):
print("Creating class", name)
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
✅ Output:
Creating class MyClass
64. What is method overloading in Python?
- Python doesn’t support true method overloading, but we can use default parameters.
Example:
class Example:
def add(self, a, b=0, c=0):
return a + b + c
obj = Example()
print(obj.add(2)) # 2
print(obj.add(2, 3)) # 5
print(obj.add(2, 3, 4)) # 9
65. What is method overriding in Python?
- A subclass redefines a method from the parent class.
Example:
class Parent:
def show(self):
print("Parent method")
class Child(Parent):
def show(self):
print("Child method")
obj = Child()
obj.show() # Child method
66. What are Python’s built-in data types?
Data Type | Example |
---|---|
int | 10 |
float | 3.14 |
str | "Hello" |
list | [1, 2, 3] |
tuple | (1, 2, 3) |
dict | {"a": 1, "b": 2} |
set | {1, 2, 3} |
67. What is the zip()
function in Python?
- Combines multiple iterables element-wise.
Example:
names = ["Alice", "Bob"]
ages = [25, 30]
combined = list(zip(names, ages))
print(combined) # [('Alice', 25), ('Bob', 30)]
68. What is the purpose of __slots__
in Python?
__slots__
reduces memory usage by preventing dynamic attribute creation.
Example:
class Person:
__slots__ = ["name", "age"]
p = Person()
p.name = "Alice" # ✅ Allowed
# p.city = "NY" # ❌ Error (Not in __slots__)
69. What is a coroutine in Python?
- Coroutines use
async
andawait
for asynchronous programming.
Example:
import asyncio
async def greet():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(greet())
✅ Output:
Hello
(World appears after 1 second)
70. What is functools.lru_cache()
used for?
- Caches function results to speed up repeated calls.
Example:
from functools import lru_cache
@lru_cache(maxsize=3)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(10)) # Faster with caching
71. What is the difference between deepcopy()
and copy()
in Python?
Function | Behavior |
---|---|
copy.copy() | Creates a shallow copy (copies references, not objects) |
copy.deepcopy() | Creates a deep copy (recursively copies all objects) |
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
print(shallow) # [[99, 2], [3, 4]] (Shallow copy affected)
print(deep) # [[1, 2], [3, 4]] (Deep copy unaffected)
72. What is Python’s super()
function?
- Used to call methods from a parent class in a child class.
Example:
class Parent:
def show(self):
print("Parent method")
class Child(Parent):
def show(self):
super().show() # Calls Parent's show()
print("Child method")
obj = Child()
obj.show()
✅ Output:
Parent method
Child method
73. What is the enumerate()
function in Python?
- Adds an index to an iterable.
Example:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
✅ Output:
1 apple
2 banana
3 cherry
74. What is the difference between @staticmethod
and @classmethod
?
Decorator | Access | First Argument |
---|---|---|
@staticmethod | No access to class or instance variables | None |
@classmethod | Works with class variables | cls |
Example:
class Demo:
class_var = "Hello"
@staticmethod
def static_method():
print("Static Method")
@classmethod
def class_method(cls):
print("Class Method:", cls.class_var)
Demo.static_method() # Static Method
Demo.class_method() # Class Method: Hello
75. How do you merge two dictionaries in Python?
Example 1: Using update()
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2)
print(dict1) # {'a': 1, 'b': 3, 'c': 4}
Example 2: Using **
(Python 3.5+)
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 3, 'c': 4}
76. What is the difference between OrderedDict
and a regular dictionary?
- Before Python 3.7:
OrderedDict
maintains insertion order, but regular dicts don’t. - Python 3.7+: Regular
dict
also maintains insertion order.
Example:
from collections import OrderedDict
ordered = OrderedDict()
ordered["a"] = 1
ordered["b"] = 2
ordered["c"] = 3
print(ordered) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
77. What is the namedtuple
in Python?
- Creates lightweight immutable objects with named fields.
Example:
from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
p = Person(name="Alice", age=25)
print(p.name, p.age) # Alice 25
78. What is Python’s deque
and why is it useful?
deque
(double-ended queue) allows fast appends & pops from both ends.
Example:
from collections import deque
dq = deque([1, 2, 3])
dq.append(4) # Adds to right
dq.appendleft(0) # Adds to left
dq.pop() # Removes from right
dq.popleft() # Removes from left
print(dq) # deque([2, 3])
79. What is the difference between split()
and partition()
in Python?
Method | Behavior |
---|---|
split() | Splits into a list of substrings |
partition() | Splits into 3 parts: before, separator, after |
Example:
text = "hello world"
print(text.split(" ")) # ['hello', 'world']
print(text.partition(" ")) # ('hello', ' ', 'world')
80. How do you convert a string to bytes in Python?
Example:
text = "Hello"
bytes_text = text.encode("utf-8")
print(bytes_text) # b'Hello'
81. What is the re
module in Python?
- Used for regular expressions.
Example: Matching a pattern
import re
text = "My number is 12345"
match = re.search(r"\d+", text)
print(match.group()) # 12345
82. What is the difference between group()
and groups()
in regex?
Method | Behavior |
---|---|
group() | Returns full match or specific group |
groups() | Returns all captured groups |
Example:
import re
text = "My age is 25"
match = re.search(r"My age is (\d+)", text)
print(match.group(1)) # 25
print(match.groups()) # ('25',)
83. What is memoization in Python?
- Stores computed results to speed up repeated calls.
Example: Using functools.lru_cache()
from functools import lru_cache
@lru_cache(maxsize=3)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(10)) # Faster with caching
84. What is itertools
in Python?
- Provides efficient looping utilities.
Example: Using itertools.permutations()
from itertools import permutations
items = [1, 2, 3]
perms = list(permutations(items))
print(perms) # [(1,2,3), (1,3,2), (2,1,3), ...]
85. What is the difference between max()
and min()
in Python?
Function | Purpose |
---|---|
max() | Returns the largest element |
min() | Returns the smallest element |
Example:
nums = [10, 20, 5, 30]
print(max(nums)) # 30
print(min(nums)) # 5
86. What is the difference between map()
, filter()
, and reduce()
in Python?
Function | Purpose |
---|---|
map() | Applies a function to all elements in an iterable |
filter() | Filters elements based on a function (returns True ) |
reduce() | Applies a rolling computation on an iterable |
Example:
from functools import reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, nums))
filtered = list(filter(lambda x: x % 2 == 0, nums))
summed = reduce(lambda x, y: x + y, nums)
print(squared) # [1, 4, 9, 16, 25]
print(filtered) # [2, 4]
print(summed) # 15
87. What is the difference between set
and frozenset
in Python?
Feature | set | frozenset |
---|---|---|
Mutability | Mutable | Immutable |
Hashable | No | Yes (can be used as dictionary keys) |
Example:
s = {1, 2, 3}
fs = frozenset(s)
# s.add(4) ✅ Works
# fs.add(4) ❌ Error (immutable)
88. What are Python’s os
and sys
modules used for?
os
: Interacts with the operating system (files, paths, processes).sys
: Interacts with Python runtime (arguments, path, exit).
Example:
import os, sys
print(os.getcwd()) # Get current working directory
print(sys.argv) # Command-line arguments
89. What is shutil
in Python?
- Used for file and directory operations.
Example:
import shutil
shutil.copy("file1.txt", "file2.txt") # Copies file1 to file2
90. How do you read and write JSON files in Python?
Example:
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded) # {'name': 'Alice', 'age': 25}
91. What is the difference between isinstance()
and issubclass()
?
Function | Purpose |
---|---|
isinstance(obj, Class) | Checks if obj is an instance of Class |
issubclass(Child, Parent) | Checks if Child inherits from Parent |
Example:
class A: pass
class B(A): pass
print(isinstance(B(), A)) # True
print(issubclass(B, A)) # True
92. What is the time
module used for?
- Used for time-related functions.
Example:
import time
print(time.time()) # Current timestamp
time.sleep(2) # Pauses execution for 2 seconds
93. What is the difference between sorted()
and sort()
?
Function | Behavior |
---|---|
sorted() | Returns a new sorted list (does not modify original) |
.sort() | Modifies the list in-place |
Example:
nums = [3, 1, 4, 1]
sorted_nums = sorted(nums)
nums.sort()
print(sorted_nums) # [1, 1, 3, 4]
print(nums) # [1, 1, 3, 4]
94. What are Python’s zip()
and unzip()
functions?
zip()
combines iterables.unzip
is done usingzip(*iterables)
.
Example:
names = ["Alice", "Bob"]
ages = [25, 30]
zipped = list(zip(names, ages))
unzipped = list(zip(*zipped))
print(zipped) # [('Alice', 25), ('Bob', 30)]
print(unzipped) # [('Alice', 'Bob'), (25, 30)]
95. What is defaultdict
in Python?
- Provides default values for missing keys.
Example:
from collections import defaultdict
dd = defaultdict(int) # Default value is 0
dd["a"] += 1
print(dd["a"]) # 1
print(dd["b"]) # 0 (default value)
96. What is Counter
in Python?
- Counts occurrences of elements.
Example:
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
count = Counter(nums)
print(count) # Counter({3: 3, 2: 2, 1: 1})
97. How do you use itertools.chain()
?
- Combines multiple iterables.
Example:
from itertools import chain
a = [1, 2]
b = [3, 4]
print(list(chain(a, b))) # [1, 2, 3, 4]
98. What is the purpose of with open()
in Python?
- Automatically closes the file after execution.
Example:
with open("file.txt", "w") as f:
f.write("Hello")
99. What are lambda
functions in Python?
- Anonymous one-line functions.
Example:
square = lambda x: x ** 2
print(square(4)) # 16
100. What is the difference between deepcopy()
and copy()
?
(Same as question 86, added here for completeness.)
Cracking a Capgemini Python interview requires a strong understanding of Python fundamentals, advanced topics, and real-world problem-solving skills. This comprehensive list of Top 100 Python Interview Questions provides a structured approach to mastering key concepts.
To further enhance your preparation:
✅ Practice coding challenges on platforms like LeetCode, HackerRank, and CodeSignal.
✅ Work on real-world projects to gain hands-on experience.
✅ Stay updated with the latest Python developments and best practices.
We hope this guide helps you ace your interview! 🚀 If you found this helpful, share it with others preparing for Python interviews! 💡💻