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 TypeOrdered?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+)✅ YesKeys: ❌ 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?

OperatorChecksExampleOutput
isObject identity (same memory location)a is bFalse (unless same object)
==Value equalitya == bTrue (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 TypeCopies 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?

OperatorUsed ForExample
*argsPassing multiple positional argumentsfunc(1, 2, 3)
**kwargsPassing multiple keyword argumentsfunc(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 TypeCan 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 TypeSyntaxSupports Multiple Statements?
Regular Functiondef func(): return x+y✅ Yes
lambda Functionlambda 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?

MethodUse CaseReturns Value?Affects Index?
delDeletes 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?

OperationCreates 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?

FunctionChecksSupports Inheritance?
isinstance(obj, Class)Checks if an object is an instance of a class✅ Yes
type(obj) is ClassChecks 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?

ScopeDefined InCan Be Modified?Keyword
LocalInside function✅ YesNone
NonlocalInside nested function✅ Yesnonlocal
GlobalOutside function✅ Yesglobal

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?

StatementFunctionality
breakExits loop immediately
continueSkips current iteration and moves to next
passDoes 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?

FunctionDescription
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?

FunctionPurposeReturns
map()Applies function to all itemsNew list
filter()Filters elements based on conditionNew list
reduce()Reduces list to single valueSingle 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 TypeRequires 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?

FeaturePython 2Python 3
Print Statementprint "Hello"print("Hello")
Integer Division5 / 2 = 25 / 2 = 2.5
Unicode SupportASCII by defaultUnicode by default
Iteratorsrange() returns listrange() returns iterator

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

OperatorChecksExampleOutput
==Compares valuesa == b✅ True
isCompares 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()?

MethodReadsReturns
read(size)Whole file or size bytesString
readline()Single lineString
readlines()All linesList 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?

KeywordPurpose
tryDefines a block of code to test for errors
exceptCatches and handles exceptions
elseExecutes if no exceptions occur
finallyAlways 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?

MethodPurposeExample
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?

FunctionReturns True if…Example
any()At least one element is Trueany([0, 1, 0])True
all()All elements are Trueall([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?

TypeMutable?Example
Mutable✅ Yeslist, dict, set
Immutable❌ Noint, 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()?

FunctionPurposeExample
isinstance(obj, Class)Checks if obj is an instance of Class or subclassisinstance(5, int) → ✅ True
type(obj)Returns the exact class of objtype(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 of return, 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?

FeatureGeneratorIterator
Defined usingyield__iter__() and __next__()
Memory UsageEfficientMay require more memory
Exampledef gen(): yield 1class 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()?

FunctionMutabilityReturns
sort()Modifies listNone
sorted()Returns new sorted listNew 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()?

MethodRemovesExample
delBy indexdel lst[1]
remove()By valuelst.remove(3)
pop()By index & returns valuelst.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?

StatementPurpose
breakExits the loop entirely
continueSkips the current iteration and moves to the next
passActs 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?

DecoratorPurposeFirst Argument
@staticmethodNo access to class or instance variablesNone
@classmethodWorks with class variables, not instance variablescls (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__)?

MethodPurpose
__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?

MethodPurpose
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?

OperatorCompares
==Values
isMemory 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 TypeExample
int10
float3.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 and await 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?

FunctionBehavior
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?

DecoratorAccessFirst Argument
@staticmethodNo access to class or instance variablesNone
@classmethodWorks with class variablescls

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?

MethodBehavior
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?

MethodBehavior
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?

FunctionPurpose
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?

FunctionPurpose
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?

Featuresetfrozenset
MutabilityMutableImmutable
HashableNoYes (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()?

FunctionPurpose
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()?

FunctionBehavior
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 using zip(*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! 💡💻

Leave a Reply

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