Cognizand GenC Python Cluster Mock Interview
Cognizand GenC Python Cluster Mock Interview
Questions
Here is a comprehensive set of mock interview questions for the Cognizant Gen C Python role,
categorized by difficulty. Each question includes a sample answer and keywords to look for.
Beginner Level
1. What is Python?
Answer: Python is a high-level, interpreted programming language known for its simple syntax, which
promotes readability and reduces the cost of program maintenance. It supports multiple programming
paradigms, including procedural, object-oriented, and functional programming.
Answer: Key features of Python include its simple and easy-to-learn syntax, its interpreted nature,
cross-platform compatibility, extensive standard library, and support for multiple programming
paradigms like object-oriented and procedural programming.
Answer: Keywords in Python are reserved words that have special meanings and purposes and cannot
be used as variable or function names. Examples include if , else , for , while , def , class ,
import , True , False , and None .
Answer: The primary difference is that lists are mutable, meaning their elements can be changed after
creation, while tuples are immutable, meaning they cannot be modified. Lists are defined with square
brackets [] , whereas tuples use parentheses () .
Page 1 of 13
Keywords: Mutable, immutable, square brackets, parentheses, changeable,
unchangeable.
Answer: Single-line comments in Python start with a hash symbol ( # ). For multi-line comments, you
can use triple quotes ( """ or ''' ) at the beginning and end of the block of text, although this is
technically a docstring.
Answer: Variables are used to store data values. In Python, a variable is created the moment you first
assign a value to it. You don't need to declare the type of a variable explicitly.
Answer: Python has several built-in data types, including numeric types (int, float, complex), sequence
types (list, tuple, range), text type (str), mapping type (dict), set types (set, frozenset), and boolean type
(bool).
Answer: A common way to reverse a string in Python is to use slicing with a step of -1:
my_string[::-1] .
Answer: The len() function is used to get the number of items in an object. It can be used on
sequences like strings, lists, tuples, and dictionaries.
Answer: Type casting is the process of converting a variable from one data type to another. This can be
done using functions like int() , float() , str() , etc.
Answer: The break statement is used to exit a loop prematurely. The continue statement skips
the rest of the code inside the current iteration of the loop and proceeds to the next iteration.
Answer: You define a function in Python using the def keyword, followed by the function name,
parentheses for arguments, and a colon. The function body is indented.
Answer: A dictionary is a collection of key-value pairs. It is unordered, mutable, and indexed by keys.
Dictionaries are defined with curly braces {} .
Answer: You can access a value in a dictionary by providing its key in square brackets, like
my_dict['key'] .
Answer: A set is an unordered collection of unique elements. Sets are mutable and are defined with
curly braces {} or the set() function.
Answer: You can add an element to the end of a list using the append() method. To insert an element
at a specific position, you can use the insert() method.
Page 3 of 13
18. What is the difference between == and is ?
Answer: The == operator checks for equality of values, while the is operator checks if two variables
refer to the same object in memory.
Answer: Python strings have a rich set of built-in methods to perform common operations. Examples
include upper() , lower() , split() , strip() , and replace() .
Answer: Concatenation is the process of combining two or more strings into a single string. In Python,
you can use the + operator for this.
Answer: You can get user input using the input() function, which reads a line from the input,
converts it to a string, and returns it.
Answer: A module is a file containing Python code, such as function definitions, variables, and classes.
It allows you to logically organize your Python code.
Answer: You can import a module using the import statement followed by the module name, for
example, import math .
Answer: The range() function generates a sequence of numbers. It is often used in for loops to
iterate a specific number of times.
Page 4 of 13
Keywords: Sequence of numbers, for loop, iteration.
Answer: Slicing is used to access a specific range of elements from a sequence like a list or a string.
The syntax is [start:stop:step] .
Answer: The pass statement is a null operation; nothing happens when it executes. It is used as a
placeholder in code where a statement is syntactically required but you have nothing to write.
Answer: The boolean data type represents one of two values: True or False . It is used to represent
truth values.
Answer: You can use the type() function to check the data type of a variable.
Answer: A parameter is the variable listed inside the parentheses in the function definition. An
argument is the value that is sent to the function when it is called.
Intermediate Level
Page 5 of 13
Answer: Object-Oriented Programming is a programming paradigm based on the concept of "objects,"
which can contain data in the form of fields (attributes) and code in the form of procedures (methods).
Answer: The four main principles of OOP are Encapsulation, Abstraction, Inheritance, and
Polymorphism.
Answer: A class is a blueprint for creating objects. An object is an instance of a class. The class defines
the attributes and methods that all objects of that class will have.
4. What is inheritance?
Answer: Inheritance is a mechanism in which one class acquires the properties (attributes and
methods) of another class. The class that inherits is the child class, and the class from which it inherits
is the parent class.
5. What is polymorphism?
6. What is encapsulation?
Answer: Encapsulation is the bundling of data (attributes) and methods that operate on the data into a
single unit, or class. It restricts direct access to some of an object's components.
Answer: A shallow copy creates a new object but inserts references into it to the objects found in the
original. A deep copy creates a new object and recursively copies all objects found in the original.
Page 6 of 13
8. What are list comprehensions?
Answer: List comprehensions provide a concise way to create lists. They consist of brackets
containing an expression followed by a for clause, then zero or more for or if clauses.
Answer: A lambda function is a small anonymous function. It can take any number of arguments but can
only have one expression. They are defined using the lambda keyword.
Answer: Decorators are a design pattern in Python that allows a user to add new functionality to an
existing object without modifying its structure. Decorators are usually called before the definition of a
function you want to decorate.
Answer: Generators are a simple way of creating iterators. A generator is a function that returns an
iterator object that we can iterate over (one value at a time). It uses the yield keyword.
Answer: __new__ is the first step of instance creation. It's called first and is responsible for returning
a new instance of your class. __init__ is the initializer method; it takes the instance returned by
__new__ and initializes it.
Answer: The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing
multiple threads from executing Python bytecode at the same time. This means that in CPython, only
one thread can be executing at any given time.
Page 7 of 13
Answer: *args and **kwargs are used to pass a variable number of arguments to a function.
*args is used for non-keyworded variable-length arguments, while **kwargs is for keyworded
variable-length arguments.
Answer: This block of code will only be executed when the Python script is run directly, not when it is
imported as a module into another script. It's used to make code reusable and runnable.
Answer: Python's memory management is handled by the Python Memory Manager, which uses a
private heap. It uses a combination of reference counting and a cyclic garbage collector.
Answer: Context management allows for the setup and teardown of resources automatically. The
with statement is used to wrap the execution of a block of code within methods defined by a context
manager.
Answer: An iterable is an object that can be looped over. An iterator is an object that represents a
stream of data; it returns the data one element at a time using the next() method.
Answer: Exceptions are handled using try...except blocks. The code that might raise an
exception is in the try block, and the handler is in the except block. finally and else clauses
can also be used.
Page 8 of 13
Keywords: try , except , finally , else , raise .
Answer: A module is a single Python file, while a package is a collection of modules in a directory. A
package must contain an __init__.py file (which can be empty).
Answer: A namespace is a mapping from names to objects, implemented as dictionaries. There are
different types: built-in, global, and local.
Answer: The super() function is used to call a method from a parent class. It is often used in the
__init__ method of a child class to call the parent's __init__ .
Answer: Serialization is converting a Python object into a byte stream, and deserialization is the
reverse. The pickle module is commonly used for this.
Answer: Monkey-patching refers to the dynamic modification of a class or module at runtime. This can
be used to add or change the behavior of existing code without altering the original source.
Answer: A metaclass is a class whose instances are classes. Just as a class defines how an object
behaves, a metaclass defines how a class behaves.
27. What is the difference between static methods and class methods?
Answer: A class method takes the class as its first argument ( cls ), while a static method knows
nothing about the class and just deals with its parameters. Class methods are often used as factory
Page 9 of 13
functions.
Answer: Python's main built-in data structures are lists, tuples, dictionaries, and sets.
Answer: The yield keyword is used in generator functions. It pauses the function's execution and
saves the state, so it can be resumed later from the same point.
Answer: A virtual environment is a self-contained directory that contains a Python installation for a
particular version, plus additional packages. It allows you to work on multiple projects with different
dependencies without conflicts.
Advanced Level
Answer: The for loop in Python works with iterators. When a for loop is used, Python calls
__iter__() on the iterable to get an iterator. Then, it repeatedly calls __next__() on the iterator
to get the next item until a StopIteration exception is raised.
Answer: Python primarily uses reference counting. Every object has a reference count, which is
changed when a reference is made or removed. When the count reaches zero, the object's memory is
deallocated. To handle reference cycles, Python also has a cyclic garbage collector.
Page 10 of 13
Answer: The MRO is the order in which Python searches for a method in a class hierarchy in case of
multiple inheritance. Python uses the C3 linearization algorithm to determine the MRO.
Answer: Descriptors are Python objects that implement a __get__ , __set__ , or __delete__
method. They are used to control access to an attribute of an object. Properties are a common use of
descriptors.
Answer: Due to the Global Interpreter Lock (GIL), true parallelism with threads is not possible in
CPython for CPU-bound tasks. To achieve parallelism, you can use the multiprocessing module,
which spawns new processes, each with its own interpreter and memory, bypassing the GIL.
Answer: Coroutines are a more general form of subroutines. They are program components that
generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and
resumed. Python's async/await syntax is built upon coroutines.
Answer: Performance can be optimized by using efficient data structures, built-in functions, and
libraries like NumPy. Profiling the code to identify bottlenecks is crucial. For CPU-bound tasks, C
extensions or libraries like Cython can be used.
8. What are some new features in recent Python versions (e.g., 3.8, 3.9, 3.10)?
Answer: Python 3.8 introduced assignment expressions ( := ), 3.9 brought dictionary union operators
( | ), and 3.10 introduced structural pattern matching ( match...case ).
Page 11 of 13
Answer: Python uses duck typing, which means an object's type is less important than the methods it
defines. If it acts like a duck, it's a duck. Strong typing means an object's type is enforced, and
operations on objects of the wrong type are not allowed.
Answer: Security measures include validating user input to prevent injection attacks, using secure
libraries for sensitive operations, managing dependencies to avoid vulnerabilities, and following secure
coding practices.
Answer: WSGI (Web Server Gateway Interface) is the standard for synchronous Python web
applications, while ASGI (Asynchronous Server Gateway Interface) is the standard for asynchronous
applications. ASGI allows for long-lived connections, like WebSockets.
Answer: multithreading allows for concurrent execution within the same process, sharing
memory, and is suitable for I/O-bound tasks. multiprocessing creates separate processes with
their own memory, allowing for parallel execution on multiple CPUs, which is ideal for CPU-bound tasks.
Answer: Function annotations are a way of associating arbitrary metadata with function arguments and
return values. They are stored in the __annotations__ attribute of the function and are often used
for type hints.
Answer: The __slots__ attribute allows you to explicitly declare data members and prevent the
creation of __dict__ for each instance. This can save memory for classes with many instances.
Page 12 of 13
Answer: A singleton pattern ensures that a class has only one instance. This can be implemented using
a decorator, a base class, or by overriding the __new__ method.
Answer: Memoization is an optimization technique used to speed up programs by storing the results of
expensive function calls and returning the cached result when the same inputs occur again.
Answer: A process is an instance of a program running with its own memory space. A thread is a unit of
execution within a process, and threads within the same process share the same memory space.
18. What are some common design patterns you have used in Python?
Answer: Candidates should discuss common design patterns like Singleton, Factory, Decorator, and
Observer, and provide examples of their implementation in Python.
Answer: Python's standard integers have arbitrary precision, meaning they can grow to accommodate
any value. This effectively means that integer overflow is not an issue in Python as it is in fixed-size
integer types in other languages.
Answer: sys.argv is a list in Python that contains the command-line arguments passed to a script.
sys.argv[0] is the script name itself.
Page 13 of 13