BASIC PYTHON:
Q1. Can you explain the concept of negative indexing in Python lists?
Answer: In Python lists, negative indexing allows access to elements from the end of the list.
Index -1 refers to the last element, -2 to the second-to-last, and so on. It provides a convenient
way to retrieve elements if you don’t know the list’s length. It also simplifies codes and
enhances their efficiency.
Q2. Can you differentiate between global and local variables in Python?
Answer: In Python, the global variables are declared outside functions and are accessible
throughout the entire program. Local variables are declared inside functions and have scope
limited to that function. Global variables can be modified globally, while local variables are
confined to their respective functions, enhancing encapsulation and modularity.
Q3. What is the method for creating an array in Python?
Answer: In Python, arrays are commonly created using the array module or, more commonly,
using lists. Lists are dynamic arrays that can hold elements of different data types. To create a
list, use square brackets and separate elements with commas. Example: my_list = [1, 2, 3].
Q4. Can you name the two primary loop statements in Python?
Answer: The two major loop statements in Python are “for” and “while.” The “for” loop iterates
over a sequence, such as a list or range, while the “while” loop continues executing as long as a
specified condition remains true. These loops are fundamental for repetitive tasks and control
flow in Python programs.
Q5. Can you define modules in Python?
Answer: Modules in Python are organizational units that group related code together. They
consist of Python files containing functions, classes, and variables. Modules provide a way to
organize and reuse code, promoting modularity. They can be imported into other Python
scripts, enhancing code maintainability and readability.
Q6. Explain the types of functions in Python.
Answer: In Python, a function is a reusable block of code that performs a specific task. Python
functions enhance code modularity, readability, and reusability. There are two main types of
functions in Python:
▪ Built-in Functions:These functions are part of the Python standard library and are
readily available for use without the need for explicit definition. Examples include print(),
len(), and type().
▪ User-Defined Functions:These functions are created by the user to encapsulate a
specific set of actions. They are defined using the def keyword, followed by the function
name, parameters, and a code block.
Q7. What is the difference between loc and iloc?
Answer: loc and iloc are two important methods used for accessing and manipulating data
within a [Link] difference between loc and iloc is mentioned below:
Criteria loc iloc
It uses integer-based indexing,
Selection It uses label-based indexing, meaning you refer
Method to the actual row and column labels. where you specify integer positions of rows and columns.
Syntax It uses row and column labels directly. It uses integer indices for rows and columns.
With iloc, slicing is inclusive for the
Inclusive With loc, slicing is inclusive on both ends,
Slicing considering the specified start and end labels. start index and exclusive for the end index.
It can select rows by integer locations
It can select rows with a particular label and
Subsetting condition. regardless of the DataFrame index.
Example [Link][1, ‘column_name’] [Link][1, 0]
Q8. Can you explain how memory is managed in Python?
Answer: In Python, memory management is handled by the Python Memory Manager, which
utilizes a private heap space for storing objects and data structures. Python employs automatic
memory management through a system called garbage collection. The key components include:
▪ Reference Counting: Python uses a reference counting mechanism to keep track of the
number of references to each object. When an object’s reference count drops to zero, it
is deallocated.
▪ Garbage Collection: Python’s garbage collector identifies and reclaims memory occupied
by objects with zero reference counts. This helps in freeing up memory that is no longer
in use.
▪ Memory Pool: Python uses a memory pool to efficiently allocate and manage memory
for small objects. It helps avoid the overhead of frequent memory allocation and
deallocation.
▪ Automatic Memory Management: Python’s memory management is automatic, and
developers generally do not need to explicitly allocate or deallocate memory. The system
handles memory tasks, making it easier for developers to focus on coding.
Q9. What is the difference between a tuple and a list?
Answer: In Python, both tuples and lists are data structures used to store collections of items.
However, here is the difference between a tuple and a list in Python:
Criteria Tuple List
Tuples are immutable, meaning their
Lists are mutable and
elements cannot be changed after
Mutability creation. allow modifications.
Lists use square
Tuples are defined using parentheses (
Syntax ). brackets [ ].
Elements can be modified
Elements in tuples cannot be modified
Modification once assigned, ensuring data integrity. after the assignment.
Lists are slower, especially
Tuples are slightly faster for iteration
Performance and indexing due to their immutability. during dynamic resizing.
Lists are dynamic and consume
Memory Tuples consume less memory as they
Usage are fixed in size. more memory.
Lists are preferred for dynamic
data that requires modifications and operations.
Tuples are suitable for scenarios where
data should remain unchanged,
Use Cases providing integrity.
Q10. Can you explain the difference between modules and libraries?
Answer: Python modules help in modularizing code, promoting code reusability and
maintainability. On the other hand, a library is a collection of modules that can be utilized to
perform various tasks. Python libraries are essentially pre-written code that developers can use
to avoid reinventing the wheel and expediting their programming tasks.
Q11. What is a map function in Python?
Answer: In Python, the map() function is a built-in higher-order function that applies a specified
function to all items in an iterable (such as a list) and returns an iterable of the results. It takes
two arguments: the function to apply and the iterable. It provides a concise and efficient way to
perform operations enhancing code readability and simplicity without the need for explicit
loops.
Q12. How would you comment with multiple lines in Python?
Answer: In Python, you can use triple quotes (”’ or “””) to create multiline comments. This
allows you to comment out multiple lines without using the ‘#’ symbol at the beginning of each
line. Example:
'''
This is a
multiline comment
in Python.
'''
Q13. Do you know what is pep 8?
Answer: PEP 8, or Python Enhancement Proposal 8, is the style guide for Python code. It
provides conventions for writing clean, readable, and consistent Python code. Created by Guido
van Rossum, PEP 8 covers topics such as indentation, naming conventions, and other practices
to enhance code quality and maintainability.
Q14. Can you explain what are decorators in Python?
Answer: Decorators in Python are functions that modify or extend the behavior of other
functions or methods. They allow you to wrap additional functionality around existing functions
without modifying their code. Decorators are commonly used for tasks like logging, access
control, and code instrumentation in a concise and reusable manner.
Q15. How will you shuffle the elements of a list in Python?
Answer: To shuffle elements of a list in Python, use the shuffle function from the random
module. Import the module, then apply [Link](your_list). This rearranges the elements
randomly. Example:
import random
my_list = [1, 2, 3, 4, 5]
[Link](my_list)
Check out a list of all the TCS interview questions with answers and impress your recruiters with
ease.
TCS Python Interview Questions for Mid-Level Developers
If you are applying for a mid-level Python developer job at TCS, it is important to prepare for the
interview by reviewing some common interview questions. Going through these questions can
help ace your interview. Here are TCS Python developer interview questions for mid-level
positions:
Q16. Can you differentiate between SciPy and NumPy?
Answer: NumPy and SciPy are complementary libraries in Python. NumPy focuses on
fundamental array operations, providing support for large, multi-dimensional arrays and
matrices. SciPy builds on NumPy, by offering additional functionality for scientific computing,
including optimization, integration, interpolation, and signal processing, making it a
comprehensive toolkit for scientific and technical computing.
Q17. Does Python employ access specifiers in its object-oriented programming paradigm?
Answer: Python does not have explicit access specifiers like “private” or “public” as in some
other languages. Instead, it relies on naming conventions. Attributes with a single leading
underscore (e.g., _variable) are considered conventionally private, while those with a double
leading underscore (e.g., __variable) undergo name mangling for stronger privacy.
Q18. Is there an equivalent to scanf() or sscanf() in Python?
Answer: In Python, the input() function can be used to read user input, somewhat analogous to
scanf() in C. For more advanced formatting and parsing, the re-module can be employed.
However, Python doesn’t have a direct equivalent to sscanf(); string manipulation and regular
expressions are commonly used instead.
Q19. What are the methods available for incorporating view functions into Django’s [Link] file?
Answer: In Django’s [Link], view functions can be added using:
▪ Function-Based Views: Directly reference functions.
▪ Class-Based Views: Use as view() method when associating a class-based view.
▪ URL Patterns: Use the path() or re_path() functions to map URLs to views.
▪ Include(): Organize URL patterns into separate files.
Q20. Can you explain the location of source files, such as [Link], [Link], and [Link],
within the Python standard library?
Answer: The source files for standard Python modules like [Link], [Link], and [Link] are
part of the Python standard library. They are typically located in the Lib directory of the Python
installation. Users can access and explore these files to understand the implementation details
of the corresponding modules.
Q21. Are there any interfaces for database packages in Python?
Answer: Yes, Python offers various interfaces for database packages. The standard library
includes the SQLite3 module for SQLite databases. Additionally, popular third-party libraries
such as SQLAlchemy, Django ORM, and psycopg2 (for PostgreSQL) provide powerful and flexible
database interfaces, enabling seamless interaction with different database systems.
Q22. Can a Python class inherit from more than one parent class?
Answer: Yes, a Python class can inherit from more than one parent class, thereby supporting
multiple inheritance. It can be achieved by listing multiple parent classes in the class definition.
Q23. Can you explain the term Tkinter?
Answer: The term “Tkinter” refers to a standard GUI (Graphical User Interface) toolkit in
Python. Tkinter is a built-in library that provides tools for creating desktop applications with
graphical interfaces. It is based on the Tk GUI toolkit and is widely used for developing user-
friendly applications in Python.
Q24. Can you explain the use of the ‘with’ statement and its syntax?
Answer: The ‘with’ statement in Python is used for context management, ensuring proper setup
and cleanup of resources. Its syntax is:
with context_expression as target_variable:
# Code block inside the 'with' statement
Here, ‘context_expression’ is an object that supports the context management protocol, and
‘target_variable’ is the variable to which the result of the expression is assigned.
Q25. Can you describe the split(), sub(), and subn() methods found within Python’s ‘re’ module?
Answer: The re-module in Python provides several methods for working with regular
expressions. Here’s a description of the split(), sub(), and subn() methods:
▪ split() Method: The split() method is used to split a string into a list based on a specified
regular expression pattern. It takes the pattern as an argument and returns a list of
substrings.
▪ sub() Method: The sub() method is used for replacing occurrences of a pattern in a
string with a specified replacement. It takes three arguments: the pattern to search for,
the replacement string, and the input string.
▪ subn() Method: The subn() method is similar to sub(), but it returns a tuple containing
the modified string and the number of substitutions made.
Q26. What do you know about iterators in Python?
Answer: In Python, an iterator is an object that represents a stream of data and enables
iteration over a sequence of elements, one at a time. It follows the iterator protocol,
implementing two methods: __iter__() and __next__().
▪ The __iter__() method returns the iterator object itself and is called when an iterator is
initialized.
▪ The __next__() method returns the next element in the sequence and is called for each
subsequent iteration. When there are no more elements, it raises the StopIteration
exception.
Q27. Do you know what *args and **kwargs mean in Python?
Answer: In Python, *args and **kwargs are used to pass a variable number of arguments to a
function.
▪ *args allows a function to accept any number of positional arguments. It collects them
into a tuple.
▪ **kwargs allows a function to accept any number of keyword arguments. It collects
them into a dictionary.
Q28. What do you know about Dict and List Comprehension?
Answer: Python comprehensions provide a way to create modified and filtered lists,
dictionaries, or sets from a given list, dictionary, or set. They are a powerful feature in Python
that allows the creation of concise expressions for creating lists, dictionaries, and sets.
Comprehensions eliminate the need for explicit loops, which can help reduce the size of your
code and save time during development.
Q29. What is the difference between range & xrange?
Answer: Here’s a table outlining the differences between range and xrange:
Feature range xrange
It creates a list
containing all elements
in the range. It It generates elements on
consumes more
the fly, consuming minimal memory
Memory memory, especially for
Usage large ranges. regardless of range size.
Type It returns a list type. It returns an xrange object, an iterator-like type.
It is preferred for large ranges or
It is suitable when you
situations where memory efficiency is crucial,
need an actual list of
Usage elements. as it generates elements as needed.
It is present in Python 2 It is only available in Python
and Python 3 but
2 as Python 3 no longer uses xrange().
behaves differently in
Compatibility each. Instead, range() is used.
Q30. What is the purpose of the “is”, “not” and “in” operators?
Answer: In Python, the “is” operator, the “not” operator, and the “in” operator serve different
purposes:
▪ “is” Operator: The “is” operator in Python is used for identity comparison. It checks if
two objects refer to the same memory location, determining if they are the same object.
▪ “not” Operator: The “not” operator is a logical operator in Python used for negation. It
returns True if the operand is False, and vice versa. It negates the truth value of the
given expression.
▪ “in” Operator: The “in” operator is used to test membership. It checks if a specified
value exists in a sequence (like a string, list, or tuple), returning True if the value is
present and False otherwise.
TCS Python Developer Interview Questions for Experienced Professionals
It is essential to delve into TCS Python developer interview questions for an experienced role.
Adequate preparation ensures that you can confidently navigate complex queries and showcase
your seasoned expertise. Here are the interview questions to ace TCS’s senior-level interviews:
Q31. Can you write code to reverse a string in Python?
Answer: Certainly! Here’s a simple Python code to reverse a string:
def reverse_string(input_string):
return input_string[::-1]
# Example
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
print("Original String:", original_string)
print("Reversed String:", reversed_string)
This code defines a function reverse_string that takes an input string and returns its reverse
using slicing ([::-1]). The example then demonstrates its usage with a sample string.
Q32. Can you briefly explain how Python implements dynamic typing?
Answer: Python implements dynamic typing by allowing variables to reference objects without
explicit type declarations. The type of a variable is determined at runtime based on the assigned
object. Here is an example:
x=5 # integer
x = 'hello' # string
x = [1, 2, 3] # list
Here, x dynamically changes its type as it is assigned different values. This flexibility simplifies
code but requires careful consideration to avoid unexpected behavior.
Q33. How can you achieve Multithreading in Python?
Answer: In Python, multithreading is achieved using the threading module. The threading
module paves the way to create and manage threads. However, due to the Global Interpreter
Lock (GIL) in CPython, multithreading is more suitable for I/O-bound tasks in comparison to
CPU-bound tasks. For CPU-bound tasks, multiprocessing is recommended.
Q34. What is the main purpose of using cx_Freeze?
Answer: The primary purpose of cx_Freeze is to create standalone executables from Python
scripts. By “freezing” a Python application, it bundles the Python interpreter and all necessary
dependencies into a single executable file. This makes it easier to distribute Python applications
to users who may not have Python installed on their systems.
Q35. How can you debug an extension in Python?
Answer: To debug a Python extension, I can use tools like gdb for C extensions or Python’s built-
in pdb debugger. Set breakpoints, inspect variables, and step through the code to identify and
fix issues. Additionally, print statements and logging can aid in debugging extension modules.
Q36. What makes Django a preferred framework for web development in Python?
Answer: Django is a high-level Python web framework popular for its simplicity, scalability, and
robustness. It follows the DRY or “don’t repeat yourself” principle, promoting efficient and
maintainable code. Django provides an ORM, built-in admin panel, security features, and
extensive documentation, making it ideal for the rapid development of scalable and secure web
applications.
Q37. How can you evaluate an arbitrary Python expression from C?
Answer: To evaluate an arbitrary Python expression from C, I use the Python/C API. This
involves using functions like PyRun_SimpleString or PyRun_String to execute Python code from
within a C program. This API provides a bridge between C and Python, allowing seamless
integration and code execution.
Q38. Can you demonstrate the syntax used to instantiate a class in Python?
Answer: To create an instance of a class in Python, use the class name followed by parentheses.
For example, if the class is named MyClass, the syntax for instantiation is obj = MyClass(). This
invokes the class constructor, creating a new object or instance of that class for further use.
Q39. Explain the mechanisms through which arguments are transferred to functions in Python.
Answer: In Python, arguments are transferred to functions using a combination of positional,
keyword, and default parameters. Python doesn’t strictly follow “pass by value” or “pass by
reference” like some languages; instead, it is more accurately described as “pass by object
reference” due to its unique memory management.
Q40. What is the lambda function in Python?
Answer: A lambda function in Python is an anonymous, small, and inline function defined using
the lambda keyword. It allows the creation of simple functions without the need for a formal
function definition using def.
Lambda functions are typically used for short-lived operations, often in situations where a full
function definition would be overly verbose. They are particularly useful in functions like map(),
filter(), and sorted() where a simple function is required for a short duration.
Q41. Differentiate between append() and extend() methods?
Answer: The append() and extend() methods in Python are used to add elements to lists, but
they differ in their behavior:
▪ append() Method:The append() method is used to add a single element to the end of a
list. It takes one argument, the element to be added, and appends it to the list.
Syntax: [Link](element)
▪ extend() Method:The extend() method is used to add multiple elements to the end of a
list. It takes an iterable (e.g., a list, tuple, or string) as an argument and adds its elements
to the list.
Syntax: [Link](iterable)
Q42. Describe how Python Flask handles database requests.
Answer: Flask provides flexibility in handling database requests, allowing developers to choose
from various approaches based on their preferences and project requirements. The three
common ways to request a database in Flask include:
▪ before_request() decorator: It is used to register a function that will be executed before
each request is processed. It is commonly employed to set up resources, establish
database connections, or perform any pre-processing tasks needed for the request.
▪ after_request() decorator: It is used to register a function that will be executed after
each request is processed but before the response is sent to the client. It allows
developers to modify the response or perform clean-up tasks.
▪ teardown_request() decorator: It is used to register a function that will be executed
after each request, regardless of whether an exception occurred during processing. It is
commonly used for clean-up tasks, such as closing database connections or releasing
resources.
Q43. Describe how is multi-threading achieved in Python.
Answer: In Python, multi-threading is achieved using the threading module. It allows the
creation of threads, each running concurrently. Python’s Global Interpreter Lock (GIL) limits true
parallel execution, but threading is beneficial for I/O-bound tasks, providing concurrency by
switching between threads during blocking operations, maximizing overall performance.
Q44. Can you explain monkey patching in Python?
Answer: Monkey patching in Python involves dynamically modifying or extending a module or
class during runtime. It’s often used to add, modify, or override methods or attributes without
changing the source code.
Q45. Are you familiar with SVM?
Answer: Yes, I’m familiar with Support Vector Machines (SVM). It is a supervised machine-
learning algorithm used for classification and regression tasks. It works by finding the optimal
hyperplane that best separates data points into different classes in a high-dimensional space.