0% found this document useful (0 votes)
126 views105 pages

Data Structures in Python Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
126 views105 pages

Data Structures in Python Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CAMPUS2CAREER

Data Structures Using Python

COGNIZANT

MALLA REDDY COLLEGE OF ENGINEERING


&TECHNOLOGY

(Autonomous Institution–UGC, [Link] India) Recognized


under2(f)and12(B) of UGC ACT1956 (Affiliated to
JNTUH,Hyderabad,ApprovedbyAICTE-AccreditedbyNBA&NAAC–
‘A’GradeISO9001:2015Certified) Maisammaguda,
Dhulapally([Link]),Secunderabad–
500100,TelanganaState,India

1
Python is one of the most popular programming languages. It’s simple to use,
packed with features and supported by a wide range of libraries and
frameworks. Its clean syntax makes it beginner-friendly. It's
 A high-level language, used in web development, data science,
automation, AI and more.
 Known for its readability, which means code is easier to write, understand
and maintain.
 Backed by library support, so we don’t have to build everything from
scratch, there’s probably a library that already does what we need.
Why to Learn Python?
 Requires fewer lines of code compared to other programming languages.
 Provides Libraries / Frameworks like Django, Flask, Pandas, Tensorflow,
Scikit-learn and many more for Web Development, AI/ML, Data Science
and Data Analysis
 Cross-platform, works on Windows, Mac and Linux without major
changes.
 Used by top tech companies like Google, Netflix and NASA.
 Many Python coding job opportunities in Software Development, Data
Science and AI/ML.

Python Introduction
Python was created 1991 with focus on code readability and express concepts in
fewer lines of code.
 Simple and readable syntax makes it beginner-friendly.
 Runs seamlessly on Windows, macOS and Linux.
 Includes libraries for tasks like web development, data analysis and
machine learning.
 Variable types are determined automatically at runtime, simplifying code
writing.
 Supports multiple programming paradigms, including object-oriented,
functional and procedural programming.

2
 Free to use, distribute and modify.

Understanding Hello World Program in Python


 Hello, World! in python is the first python program which we learn
when we start learning any program. It’s a simple program that displays
the message “Hello, World!” on the screen.

Here’s the “Hello World” program:


# This is a comment. It will not be executed.

print("Hello, World!")

How does this work:


 print() is a built-in Python function that tells the computer to show
something on the screen.

3
 The message "Hello, World!" is a string, which means it's just text. In
Python, strings are always written inside quotes (either single ' or double
").
 Anything after # in a line is a comment. Python ignores comments when
running the code, but they help people understand what the code is doing.
 Comments are helpful for explaining code, making notes or skipping
lines while testing.
We can also write multi-line comments using triple quotes:
"""
This is a multi-line comment.
It can be used to describe larger sections of code.
"""
Indentation in Python
In Python, Indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All statements
with the same level of indentation are considered part of the same block.
Indentation is achieved using whitespace (spaces or tabs) at the beginning of
each line. The most common convention is to use 4 spaces or a tab, per level of
indentation.
print("I have no indentation")
print("I have tab indentaion")

Famous Application Built using Python


 YouTube: World’s largest video-sharing platform uses Python for
features like video streaming and backend services.
 Instagram: This popular social media app relies on Python’s simplicity
for scaling and handling millions of users.
 Spotify: Python is used for backend services and machine learning to
personalize music recommendations.
 Dropbox: The file hosting service uses Python for both its desktop client
and server-side operations.

4
 Netflix: Python powers key components of Netflix’s recommendation
engine and content delivery systems (CDN).
 Google: Python is one of the key languages used in Google for web
crawling, testing and data analysis.
 Uber: Python helps Uber handle dynamic pricing and route optimization
using machine learning.
 Pinterest: Python is used to process and store huge amounts of image
data efficiently.

Input and Output in Python


Understanding input and output operations is fundamental to Python
programming. With the print() function, we can display output in various
formats, while the input() function enables interaction with users by gathering
input during program execution.
Taking input in Python
Python's input() function is used to take user input. By default, it returns the
user input in form of a string.
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!
The code prompts the user to input their name, stores it in the variable "name"
and then prints a greeting message addressing the user by their entered name.

Printing Output using print() in Python


At its core, printing output in Python is straightforward, thanks to the print()
function. This function allows us to display text, variables and expressions on
the console. Let's begin with the basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within double
quotes. When executed, this statement will output the text to the console.

5
print("Hello, World!")

Output
Hello, World!
Printing Variables
We can use the print() function to print single and multiple variables. We can
print multiple variables by separating them with commas. Example:
# Single variable
s = "Bob"
print(s)

# Multiple Variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)

Take Multiple Input in Python


We are taking multiple input from the user in a single line, splitting the values
entered by the user into separate variables for each value using the split()
method. Then, it prints the values with corresponding labels, either two or three,
based on the number of inputs provided by the user.
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)

6
print("Number of girls: ", y)

# taking three inputs at a time


x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15

How to Change the Type of Input in Python


By default input() function helps in taking user input as string. If any user wants
to take input as int or float, we just need to typecast it.
Print Names in Python
The code prompts the user to input a string (the color of a rose), assigns it to the
variable color and then prints the inputted color.
# Taking input as string
color = input("What color is rose?: ")

7
print(color)
Output
What color is rose?: Red
Red
Print Numbers in Python
The code prompts the user to input an integer representing the number of roses,
converts the input to an integer using typecasting and then prints the integer
value.
# Taking input as int
# Typecasting to int
n = int(input("How many roses?: "))
print(n)
Output
How many roses?: 88
Print Float/Decimal Number in Python
The code prompts the user to input the price of each rose as a floating-point
number, converts the input to a float using typecasting and then prints the price.
# Taking input as float
# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)
Output
Price of each rose?: 50.3050.3
Find DataType of Input in Python
In the given example, we are printing the type of variable x. We will determine
the type of an object in Python.
a = "Hello World"
b = 10
c = 11.22

8
d = ("Geeks", "for", "Geeks")
e = ["Geeks", "for", "Geeks"]
f = {"Geeks": 1, "for":2, "Geeks":3}

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))

Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>
<class 'dict'>
Output Formatting
Output formatting in Python with various techniques including the format()
method, manipulation of the sep and end parameters, f-strings and the versatile
% operator. These methods enable precise control over how data is displayed,
enhancing the readability and effectiveness of your Python programs.
Example 1: Using Format()
amount = 150.75
print("Amount: ${:.2f}".format(amount))

Output

9
Amount: $150.75
Example 2: Using sep and end parameter
# end Parameter with '@'
print("Python", end='@')
print("GeeksforGeeks")

# Seprating with Comma


print('G', 'F', 'G', sep='')

# for formatting a date


print('09', '12', '2016', sep='-')

# another example
print('pratik', 'geeksforgeeks', sep='@')

Output
Python@GeeksforGeeks
GFG
09-12-2016
pratik@geeksforgeeks
Example 3: Using f-string
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Output
Hello, My name is Tushar and I'm 23 years old.
Example 4: Using % Operator

10
We can use '%' operator. % values are replaced with zero or more value of
elements. The formatting using % is similar to that of ‘printf’ in the C
programming language.
 %d –integer
 %f – float
 %s – string
 %x –hexadecimal
 %o – octal
# Taking input from the user
num = int(input("Enter a value: "))

add = num + 5

# Output
print("The sum is %d" %add)
Output
Enter a value: 50The sum is 55
Taking Conditional User Input in Python
In Python, taking conditional user input means getting input from the user and
making decisions based on that input. You usually use the input() function to get
the value and then use if-else statements to check conditions.
 input() is used to take user input as a string.
 You can use int() or float() to convert it if needed.
 Use if, elif, and else to apply conditions to the input.

Python Variables
variables are used to store data that can be referenced and manipulated during
program execution. A variable is essentially a name that is assigned to a value.

11
Unlike many other programming languages, Python variables do not require
explicit declaration of type. The type of the variable is inferred based on the
value assigned.
Variables act as placeholders for data. They allow us to store and reuse values in
our program.

Example:
# Variable 'x' stores the integer value 10
x=5

# Variable 'name' stores the string "Samantha"


name = "Samantha"

print(x)
print(name)

Output
5
Samantha
In this article, we’ll explore the concept of variables in Python, including their
syntax, characteristics and common operations.
Table of Content
 Rules for Naming Variables
 Assigning Values to Variables
 Multiple Assignments
 Type Casting a Variable
 Getting the Type of Variable
 Object Reference in Python
 Delete a Variable Using del Keyword

12
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
 Variable names can only contain letters, digits and underscores (_).
 A variable name cannot start with a digit.
 Variable names are case-sensitive (myVar and myvar are different).
 Avoid using Python keywords (e.g., if, else, for) as variable names.
Valid Example:
age = 21
_colour = "lilac"
total_score = 90
Invalid Example:
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
Assigning Values to Variables
Basic Assignment
Variables in Python are assigned values using the = operator.
x=5
y = 3.14
z = "Hi"
Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold
different types of values during execution.
x = 10
x = "Now a string"
Multiple Assignments
Python allows multiple variables to be assigned values in a single line.
Assigning the Same Value

13
Python allows assigning the same value to multiple variables in a single line,
which can be useful for initializing variables with the same value.
a = b = c = 100
print(a, b, c)

Output
100 100 100
Assigning Different Values
We can assign different values to multiple variables simultaneously, making the
code concise and easier to read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)

Output
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one data type into
another. Python provides several built-in functions to facilitate casting,
including int(), float() and str() among others.
Basic Casting Functions
 int() - Converts compatible values to an integer.
 float() - Transforms values into floating-point numbers.
 str() - Converts any data type into a string.
Examples of Casting:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float

14
age = 25
s2 = str(age) # Cast integer to string

# Display results
print(n)
print(f)
print(s2)

Output
10
5.0
25
Getting the Type of Variable
In Python, we can determine the type of a variable using the type() function.
This built-in function returns the type of the object passed to it.
Example Usage of type()
# Define variables with different data types
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True

# Get and print the type of each variable


print(type(n))
print(type(f))
print(type(s))

15
print(type(li))
print(type(d))
print(type(bool))

Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
Object Reference in Python
Let us assign a variable x to value 5.
x=5

When x = 5 is executed, Python creates an object to represent the value 5 and


makes x reference this object.
Now, if we assign another variable y to the variable x.
y=x

16
Explanation:
 Python encounters the first statement, it creates an object for the
value 5 and makes x reference it. The second statement creates y and
references the same object as x, not x itself. This is called a Shared
Reference, where multiple variables reference the same object.
Now, if we write
x = 'Geeks'
Python creates a new object for the value "Geeks" and makes x reference this
new object.

Explanation:
 The variable y remains unchanged, still referencing the original object 5.
If we now assign a new value to y:
y = "Computer"

17
 Python creates yet another object for "Computer" and updates y to
reference it.
 The original object 5 no longer has any references and becomes eligible
for garbage collection.
Key Takeaways:
 Python variables hold references to objects, not the actual objects
themselves.
 Reassigning a variable does not affect other variables referencing the
same object unless explicitly updated.
Delete a Variable Using del Keyword
We can remove a variable from the namespace using the del keyword. This
effectively deletes the variable and frees up the memory it was using.
Example:
# Assigning value to variable
x = 10
print(x)

# Removing the variable using del


del x

# Trying to print x after deletion will raise an error

18
# print(x) # Uncommenting this line will raise NameError: name 'x' is not
defined
Explanation:
 del x removes the variable x from memory.
 After deletion, trying to access the variable x results in a NameError,
indicating that the variable no longer exists.
Practical Examples
1. Swapping Two Variables
Using multiple assignments, we can swap the values of two variables without
needing a temporary variable.
a, b = 5, 10
a, b = b, a
print(a, b)

Output
10 5
2. Counting Characters in a String
Assign the results of multiple operations on a string to variables in one line.
word = "Python"
length = len(word)
print("Length of the word:", length)

Output
Length of the word: 6
Scope of a Variable
In Python, the scope of a variable defines where it can be accessed in the
program. There are two main types of scope: local and global.
Local Variables:
 Defined within a function or block, accessible only inside that scope.

19
 Destroyed once the function/block ends.
 Temporary, used for short-term data.
Global Variables:
 Defined outside functions, accessible throughout the program.
 To modify within a function, use the global keyword.
 Persist in memory for the program’s duration, useful for shared data.

Python Operators
In Python programming, Operators in general are used to perform operations on
values and variables. These are standard symbols used for logical and arithmetic
operations. In this article, we will look into different types of Python
operators.
 OPERATORS: These are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.
Types of Operators in Python

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication and division.
In Python 3.x the result of division is a floating-point while in Python 2.x
division of 2 integers was an integer. To obtain an integer result in Python 3.x
floored (// integer) is used.
Example of Arithmetic Operators in Python:
# Variables
a = 15
b=4

# Addition

20
print("Addition:", a + b)

# Subtraction
print("Subtraction:", a - b)

# Multiplication
print("Multiplication:", a * b)

# Division
print("Division:", a / b)

# Floor Division
print("Floor Division:", a // b)

# Modulus
print("Modulus:", a % b)

# Exponentiation
print("Exponentiation:", a ** b)

Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

21
Note: Refer to Differences between / and // for some interesting facts about
these two Python operators.
Comparison of Python Operators
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Example of Comparison Operators in Python
Let's see an example of Comparison Operators in Python.
a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

Output
False
True
False
True
False
True
Logical Operators in Python
Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:

22
1. Logical not
2. logical and
3. logical or
Example of Logical Operators in Python:
a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False
Bitwise Operators in Python
Python Bitwise operators act on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Example of Bitwise Operators in Python:
a = 10
b=4

print(a & b)

23
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output
0
14
-11
14
2
40
Assignment Operators in Python
Python Assignment operators are used to assign values to the variables. This
operator is used to assign the value of the right side of the expression to the left
side operand.
Example of Assignment Operators in Python:
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a

24
print(b)

Output
10
20
10
100
102400
Identity Operators in Python
In Python, is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal
do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example of Identity Operators in Python:
a = 10
b = 20
c=a

print(a is not b)
print(a is c)

Output
True
True
Membership Operators in Python
In Python, in and not in are the membership operators that are used to test
whether a value or variable is in a sequence.

25
in True if value is found in the sequence
not in True if value is not found in the sequence
Examples of Membership Operators in Python:
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list
Ternary Operator in Python
in Python, Ternary operators also known as conditional expressions are
operators that evaluate something based on a condition being true or false. It
was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-
else making the code compact.
Syntax : [on_true] if [expression] else [on_false]
Examples of Ternary Operator in Python:
a, b = 10, 20

26
min = a if a < b else b

print(min)

Output
10
Precedence and Associativity of Operators in Python
In Python, Operator precedence and associativity determine the priorities of the
operator.
Operator Precedence in Python
This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
Example:
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:
print("Good Bye!!")

Output
610
Hello! Welcome.
Operator Associativity in Python

27
If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or
from Right to Left.
Example:
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)

Output
100.0
6
0
512

Python Keywords
Keywords in Python are reserved words that have special meanings and serve
specific purposes in the language syntax. Python keywords cannot be used as
the names of variables, functions, and classes or any other identifier.
Getting List of all Python keywords
We can also get all the keyword names using the below code.
import keyword

# printing all keywords at once using "kwlist()"


print("The list of keywords is : ")
print([Link])

28
Output:
The list of keywords are:
['False', 'None', 'True',"__peg_parser__ 'and', 'as', 'assert', 'async', 'await',
'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
How to Identify Python Keywords ?
 With Syntax Highlighting - Most of IDEs provide syntax-highlight
feature. You can see Keywords appearing in different color or style.
 Look for SyntaxError - This error will encounter if you have used any
keyword incorrectly. Note that keywords can not be used as identifiers
(variable or a function name).
What Happens if We Use Keywords as Variable Names ?
In Python, keywords are reserved words that have special meanings and cannot
be used as variable names. If you attempt to use a keyword as a variable, Python
will raise a SyntaxError. Let's look at an example:
for = 10
print(for)
Output
Hangup (SIGHUP)
File "/home/guest/sandbox/[Link]", line 1
for = 10
^
SyntaxError: invalid syntax
Let's categorize all keywords based on context for a more clear understanding.

Category Keywords

Value
True, False, None
Keywords

29
Category Keywords

Operator
and, or, not, is, in
Keywords

Control
if, else, elif, for, while, break, continue, pass, try, except, finally,
Flow
raise, assert
Keywords

Function
def, return, lambda, yield, class
and Class

Context
Manageme with, as
nt

Import and
import, from
Module

Scope and
global, nonlocal
Namespace

Async
Programmi async, await
ng

Difference Between Keywords and Identifiers

Keywords Identifiers

Reserved words in Python that have a Names given to variables,


specific meaning. functions, classes, etc.

30
Keywords Identifiers

Can be used as variable names (if


Cannot be used as variable names. not a keyword).

Examples: if, else, for, while Examples: x, number, sum, result

User-defined, meaningful names in


Part of the Python syntax. the code.

Can be defined and redefined by


They cannot be redefined or changed. the programmer.

Difference Between Variables and Keywords

Variables Keywords

Reserved words with predefined


Used to store data. meanings in Python.

Can be created, modified, and deleted by Cannot be modified or used as


the programmer. variable names.

Examples: x, age, name Examples: if, while, for

Hold values that are manipulated in the Used to define the structure of
program. Python code.

Variable names must follow naming Fixed by Python language and


rules but are otherwise flexible. cannot be altered.

31
Python Data Types
Python Data types are the classification or categorization of data items. It
represents the kind of value that tells what operations can be performed on a
particular data. Since everything is an object in Python programming, Python
data types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python:
 Numeric - int, float, complex
 Sequence Type - string, list, tuple
 Mapping Type - dict
 Boolean - bool
 Set Type - set, frozenset
 Binary Types - bytes, bytearray, memoryview

DataTypes
This code assigns variable 'x' different values of few Python data types - int,
float, list, tuple and string. Each assignment replaces the previous value,
making 'x' take on the data type and value of the most recent assignment.
# int, float, string, list and set

32
x = 50
x = 60.5
x = "Hello World"
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number, or even a complex number.
These values are defined as Python int, Python float and Python
complex classes in Python.
 Integers - This value is represented by int class. It contains positive or
negative whole numbers (without fractions or decimals). In Python, there
is no limit to how long an integer value can be.
 Float - This value is represented by the float class. It is a real number
with a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer
may be appended to specify scientific notation.
 Complex Numbers - A complex number is represented by a complex
class. It is specified as (real part) + (imaginary part)j . For example -
2+3j
a=5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>

33
<class 'float'>
<class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or
different Python data types. Sequences allow storing of multiple values in an
organized and efficient fashion. There are several sequence data types of
Python:
 Python String
 Python List
 Python Tuple
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python,
there is no character data type Python, a character is a string of length one. It is
represented by str class.
Strings in Python can be created using single quotes, double quotes or even
triple quotes. We can access individual characters of a String using index.
s = 'Welcome to the Geeks World'
print(s)

# check data type


print(type(s))

# access string with index


print(s[1])
print(s[2])
print(s[-1])

Output
Welcome to the Geeks World

34
<class 'str'>
e
l
d
List Data Type
Lists are just like arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets[].
# Empty list
a = []

# list with int values


a = [1, 2, 3]
print(a)

# list with mixed int and string


b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Access List Items
In order to access the list items refer to the index number. In Python, negative
sequence indexes represent positions from the end of the array. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write

35
List[-3]. Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second-last item, etc.
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])

print("Accessing element using negative indexing")


print(a[-1])
print(a[-3])

Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable. Tuples cannot
be modified after it is created.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values
separated by a ‘comma’ with or without the use of parentheses for grouping the
data sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a trailing
‘comma’ to make it a tuple.

36
# initiate empty tuple
tup1 = ()

tup2 = ('Geeks', 'For')


print("\nTuple with the use of String: ", tup2)

Output
Tuple with the use of String: ('Geeks', 'For')
Note - The creation of a Python tuple without the use of parentheses is known as
Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple.
tup1 = tuple([1, 2, 3, 4, 5])

# access tuple items


print(tup1[0])
print(tup1[-1])
print(tup1[-3])

Output
1
5
3
3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False. Boolean
objects that are equal to True are truthy (true), and those equal to False are falsy
(false). However non-Boolean objects can be evaluated in a Boolean context as
well and determined to be true or false. It is denoted by the class bool.

37
Example: The first two lines will print the type of the boolean values True and
False, which is <class 'bool'>. The third line will cause an error, because true is
not a valid keyword in Python. Python is case-sensitive, which means it
distinguishes between uppercase and lowercase letters.
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/[Link]", line 8, in
print(type(true))
NameError: name 'true' is not defined
4. Set Data Type in Python
In Python Data Types, Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements. The order of elements in a set
is undefined though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or
a sequence by placing the sequence inside curly braces, separated by
a ‘comma’. The type of elements in a set need not be the same, various mixed-
up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of
values, such as strings , lists , and mixed values
# initializing empty set
s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

38
s2 = set(["Geeks", "For", "Geeks"])
print("Set with the use of List: ", s2)

Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}
Access Set Items
Set items cannot be accessed by referring to an index, since sets are unordered
the items have no index. But we can loop through the set items using a for loop,
or ask if a specified value is present in a set, by using the in the keyword.
set1 = set(["Geeks", "For", "Geeks"])
print(set1)

# loop through set


for i in set1:
print(i, end=" ")

# check if item exist in set


print("Geeks" in set1)

Output
{'Geeks', 'For'}
Geeks For True
5. Dictionary Data Type
A dictionary in Python is a collection of data values, used to store data values
like a map, unlike other Python Data Types that hold only a single value as an
element, a Dictionary holds a key: value pair. Key-value is provided in the
dictionary to make it more optimized. Each key-value pair in a Dictionary is
separated by a colon : , whereas each key is separated by a ‘comma’.
Create a Dictionary in Python

39
Values in a dictionary can be of any datatype and can be duplicated, whereas
keys can’t be repeated and must be immutable. The dictionary can also be
created by the built-in function dict().
Note - Dictionary keys are case sensitive, the same name but different cases of
Key will be treated distinctly.
# initialize empty dictionary
d = {}

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(d)

# creating dictionary using dict() constructor


d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be
used inside square brackets. Using get() method we can access the dictionary
elements.
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Accessing an element using key


print(d['name'])

# Accessing a element using get

40
print([Link](3))

Output
For
Geeks
Python Data Type Exercise Questions
Below are two exercise questions on Python Data Types. We have covered list
operation and tuple operation in these exercise questions. For more exercises on
Python data types visit the page mentioned below.
Q1. Code to implement basic list operations
fruits = ["apple", "banana", "orange"]
print(fruits)
[Link]("grape")
print(fruits)
[Link]("orange")
print(fruits)

Output
['apple', 'banana', 'orange']
['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'grape']
Q2. Code to implement basic tuple operation
coordinates = (3, 5)
print(coordinates)
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])

Output
(3, 5)

41
X-coordinate: 3
Y-coordinate: 5

Conditional Statements in Python


Conditional statements in Python are used to execute certain blocks of code
based on specific conditions. These statements help control the flow of a
program, making it behave differently in different situations.
If Conditional Statement in Python
If statement is the simplest form of a conditional statement. It executes a block
of code if the given condition is true.

If
Statement
Example:
age = 20

if age >= 18:


print("Eligible to vote.")

Output

42
Eligible to vote.
Short Hand if
Short-hand if statement allows us to write a single-line if statement.
Example:
age = 19
if age > 18: print("Eligible to Vote.")

Output
Eligible to Vote.
This is a compact way to write an if statement. It executes the print statement if
the condition is true.
If else Conditional Statements in Python
Else allows us to specify a block of code that will execute if the condition(s)
associated with an if or elif statement evaluates to False. Else block provides a
way to handle all other cases that don't meet the specified conditions.

If Else
Statement
Example:
age = 10

43
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")

Output
Travel for free.
Short Hand if-else
The short-hand if-else statement allows us to write a single-line if-else
statement.
Example:
marks = 45
res = "Pass" if marks >= 40 else "Fail"

print(f"Result: {res}")

Output
Result: Pass
Note: This method is also known as ternary operator. Ternary Operator
essentially a shorthand for the if-else statement that allows us to write more
compact and readable code, especially for simple conditions.
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple
conditions , providing a way to execute different blocks of code based on which
condition is true. Using elif statements makes our code more readable and
efficient by eliminating the need for multiple nested if statements.

Example:

44
age = 25

if age <= 12:


print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")

Output
Young adult.
The code checks the value of age using if-elif-else. Since age is 25, it skips the
first two conditions (age <= 12 and age <= 19), and the third condition (age <=
35) is True, so it prints "Young adult.".
Nested if..else Conditional Statements in Python
Nested if..else means an if-else statement inside another if statement. We can
use nested if statements to check conditions within conditions.

45
Nested If Else
age = 70
is_member = True

if age >= 60:


if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")

46
Output
30% senior discount!
Ternary Conditional Statement in Python
A ternary conditional statement is a compact way to write an if-else condition in
a single line. It’s sometimes called a "conditional expression."
Example:
# Assign a value based on a condition
age = 20
s = "Adult" if age >= 18 else "Minor"

print(s)

Output
Adult
Here:
 If age >= 18 is True, status is assigned "Adult".
 Otherwise, status is assigned "Minor".
Match-Case Statement in Python
match-case statement is Python's version of a switch-case found in other
languages. It allows us to match a variable's value against a set of patterns.
Example:
number = 2

match number:
case 1:
print("One")
case 2 | 3:

47
print("Two or Three")
case _:
print("Other number")
Output:
Two or Three

Python For Loops


Python For Loops are used for iterating over a sequence like lists, tuples,
strings, and ranges.
 For loop allows you to apply the same operation to every item within
loop.
 Using For Loop avoid the need of manually managing the index.
 For loop can iterate over any iterable object, such as dictionary, list or any
custom iterators.
For Loop Example:
s = ["Geeks", "for", "Geeks"]

# using for loop with string


for i in s:
print(i)

Output
Geeks
for
Geeks
Table of Content
 Python For Loop with String
 Using range() with For Loop

48
 Control Statements [Continue, Break, Pass, Else]
 Using Enumerate with for loop
 Nested For Loops
Flowchart of Python For Loop

For Loop flowchart


Python For Loop Syntax
for var in iterable:
# statements
pass
Note: In Python, for loops only implement the collection-based iteration.
Python For Loop with String
This code uses a for loop to iterate over a string and print each character on a
new line. The loop assigns each character to the variable i and continues until all
characters in the string have been processed.
s = "Geeks"
for i in s:
print(i)

49
Output
G
e
e
k
s
Using range() with For Loop
The range() function is commonly used with for loops to generate a sequence of
numbers. It can take one, two, or three arguments:
 range(stop): Generates numbers from 0 to stop-1.
 range(start, stop): Generates numbers from start to stop-1.
 range(start, stop, step): Generates numbers from start to stop-1,
incrementing by step.
for i in range(0, 10, 2):
print(i)

Output
0
2
4
6
8
Control Statements with For Loop
Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed. Python supports the following control statements.
Continue with For Loop
Python continue Statement returns the control to the beginning of the loop.

50
# Prints all letters except 'e' and 's'

for i in 'geeksforgeeks':

if i == 'e' or i == 's':
continue
print(i)

Output
g
k
f
o
r
g
k
Break with For Loop
Python break statement brings control out of the loop.
for i in 'geeksforgeeks':

# break the loop as soon it sees 'e'


# or 's'
if i == 'e' or i == 's':
break

print(i)

Output

51
e
Pass Statement with For Loop
The pass statement to write empty loops. Pass is also used for empty control
statements, functions, and classes.
# An empty loop
for i in 'geeksforgeeks':
pass
print(i)

Output
s
Else Statement with For Loops
Python also allows us to use the else condition for loops. The else block just
after for/while is executed only when the loop is NOT terminated by a break
statement.
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break\n")

Output
1
2
3
No Break

Using Enumerate with for loop


In Python, enumerate() function is used with the for loop to iterate over an
iterable while also keeping track of index of each item.

52
li = ["eat", "sleep", "repeat"]

for i, j in enumerate(li):
print (i, j)

Output
0 eat
1 sleep
2 repeat
Nested For Loops in Python
This code uses nested for loops to iterate over two ranges of numbers (1 to 3
inclusive) and prints the value of i and j for each combination of these two
loops. \
The inner loop is executed for each value of i in outer loop. The output of this
code will print the numbers from 1 to 3 three times, as each value of i is
combined with each value of j.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)

Output
11
12
13
21
22
23
31
32

53
33

Python Functions
Python Functions is a block of statements that does a specific task. The idea is
to put some commonly or repeatedly done task together and make a function so
that instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.
Benefits of Using Functions
 Code Reuse
 Reduced code length
 Increased redability of code
Python Function Declaration
The syntax to declare a function is:

Syntax of Python Function Declaration


Types of Functions in Python
Below are the different types of functions in Python:
 Built-in library function: These are Standard functions in Python that
are available to use.
 User-defined function: We can create our own functions based on our
requirements.
Creating a Function in Python

54
We can define a function in Python, using the def keyword. We can add any
type of functionalities and properties to it as we require.
What is def ?
The def keyword stands for define. It is used to create a user-defined function.
It marks the beginning of a function block and allows you to group a set of
statements so they can be reused when the function is called.
Syntax:
def function_name(parameters):
# function body
Explanation:
 def: Starts the function definition.
 function_name: Name of the function.
 parameters: Inputs passed to the function (inside ()), optional.
 : : Indicates the start of the function body.
 Indented code: The function body that runs when called.
Example: Let’s understand this with a simple example. Here, we define a
function using def that prints a welcome message when called.
def fun():
print("Welcome to GFG")
For more information, refer to this article: Python def Keyword
Calling a Function in Python
After creating a function in Python we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that
particular function. Below is the example for calling def function Python.
def fun():
print("Welcome to GFG")

# Driver code to call a function


fun()

55
Output
Welcome to GFG
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
Syntax for functions with arguments:
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
data_type and return_type are optional in function declaration, meaning the
same function can also be written as:
def function_name(parameter) :
"""Docstring"""
# body of the function
return expression
Let's understand this with an example, we will create a simple function in
Python to check whether the number passed as an argument to the function is
even or odd.
def evenOdd(x: int) ->str:
if (x % 2 == 0):
return "Even"
else:
return "Odd"

print(evenOdd(16))
print(evenOdd(7))

Output
Even

56
Odd
The above function can also be declared without type_hints, like this:
def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"

print(evenOdd(16))
print(evenOdd(7))

Output
Even
Odd
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following function argument types in
Python:
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)
Let's discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example
illustrates Default arguments to write functions in Python.
def myFun(x, y=50):
print("x: ", x)

57
print("y: ", y)

myFun(10)

Output
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a
default value. But once we have a default argument, all the arguments to its
right must also have default values.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that
the caller does not need to remember the order of parameters.
def student(fname, lname):
print(fname, lname)

student(fname='Geeks', lname='Practice')
student(lname='Practice', fname='Geeks')

Output
Geeks Practice
Geeks Practice
Positional Arguments
We used the Position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or value) is
assigned to age. By changing the position, or if you forget the order of the
positions, the values can be used in the wrong places, as shown in the Case-2
example below, where 27 is assigned to the name and Suraj is assigned to the
age.

58
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

print("Case-1:")
nameAge("Suraj", 27)

print("\nCase-2:")
nameAge(27, "Suraj")

Output
Case-1:
Hi, I am Suraj
My age is 27

Case-2:
Hi, I am 27
My age is Suraj
Arbitrary Keyword Arguments
In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a
variable number of arguments to a function using special symbols. There are
two special symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
def myFun(*argv):
for arg in argv:

59
print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments
def myFun(**kwargs):
for key, value in [Link]():
print("%s == %s" % (key, value))

myFun(first='Geeks', mid='for', last='Geeks')

Output
first == Geeks
mid == for
last == Geeks
Docstring
The first string after the function is called the Document string or Docstring in
short. This is used to describe the functionality of the function. The use of
docstring in functions is optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)

60
Example: Adding Docstring to the function
def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")

print(evenOdd.__doc__)

Output
Function to check if the number is even or odd
Python Function within Functions
A function that is defined inside another function is known as the inner
function or nested function. Nested functions can access variables of the
enclosing scope. Inner functions are used so that they can be protected from
everything happening outside the function.
def f1():
s = 'I love GeeksforGeeks'

def f2():
print(s)

f2()

f1()

61
Output
I love GeeksforGeeks
Anonymous Functions in Python
In Python, an anonymous function means that a function is without a name. As
we already know the def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions.
def cube(x): return x*x*x # without lambda

cube_l = lambda x : x*x*x # with lambda

print(cube(7))
print(cube_l(7))

Output
343
343
Return Statement in Python Function
The return statement in Python is used to exit a function and send a value back
to the caller. It can return any data type, and if multiple values are separated by
commas, they are automatically packed into a tuple. If no value is specified, the
function returns None by default.
Syntax:
return [expression]
Explanation:
 return: Ends the function and optionally sends a value to the caller.
 [expression]: Optional value to return, defaults to None if omitted.
Example: Python Function Return Statement
def square_value(num):

62
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

Output
4
16
For more information, refer to this article: Python return statement
Pass by Reference and Pass by Value
One important thing to note is, in Python every variable name is a reference.
When we pass a variable to a function Python, a new reference to the object is
created. Parameter passing in Python is the same as reference passing in Java.
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output
[20, 11, 12, 13, 14, 15]

63
When we pass a reference and change the received reference to something else,
the connection between the passed and received parameters is broken. For
example, consider the below program as follows:
def myFun(x):
x = [20, 30, 40]

lst = [10, 11, 12, 13, 14, 15]


myFun(lst)
print(lst)

Output
[10, 11, 12, 13, 14, 15]
Another example demonstrates that the reference link is broken if we assign a
new value (inside the function).
def myFun(x):
x = 20

x = 10
myFun(x)
print(x)

Output
10
Exercise: Try to guess the output of the following code.
def swap(x, y):
temp = x
x=y
y = temp

64
x=2
y=3
swap(x, y)
print(x)
print(y)

Output
2
3
Recursive Functions in Python
Recursion in Python refers to when a function calls itself. There are many
instances when you have to build a recursive function to solve Mathematical
and Recursive Problems.
Using a recursive function should be done with caution, as a recursive function
can become like a non-terminating loop. It is better to check your exit statement
while creating a recursive function.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

Output
24
Here we have created a recursive function to calculate the factorial of the
number. It calls itself until a base case (n==0) is met.

65
Eligibility Criteria For Accenture, Campus 2025 Drive
To apply for Accenture Off Campus 2025 the candidates have to check the
eligibility criteria compulsory. If any of the aspirants applied without meeting
these criteria those applications will be rejected.
 B.E/ [Link]/ MCA students CS/ IT/ Circuit branches graduated in the
academic year of 2025, 2024, 2023 Batch are eligible.
 An aggregate of 65% and above or 7.25 CGPA and above in BE/ [Link]/
MCA at the time of the recruitment process.
 No active backlog at the time of application to Accenture
 A maximum 1-year gap in education (post 10th standard till completion
of graduation)
66
Skills Required For Accenture On Campus 2025
 Good understanding of C, Java, and Core Java concepts.
 Must have excellent verbal and oral communication skills with email
etiquette.
 Agree to work 24*7 shifts.
 Able to relocate to any location in India.
 Ability to work creatively.
 Should have a desire to work on any information system.
 Have problem-solving skills by understanding the bug.

Accenture Test Pattern 2025


First Assessment
The first assessment includes 2 stages of rounds:
1. Cognitive Ability and Technical Round
2. Coding Round

Number of Duration
Sections Topics
Questions of Time

 English Ability
Cognitive  Critical Reasoning and
50 Questions 50 Minutes
Ability Problem Solving
 Abstract Reasoning

 Common Application
Technical and MS Office 40 Questions 40 Minutes
Assessment
 Pseudo Code

67
Number of Duration
Sections Topics
Questions of Time

 Fundamentals of
Networking Security
and Cloud

 C
 C++
Coding Round  Dot Net 2 Questions 45 Minutes
 JAVA
 Python

Note: Coding Round is a mandatory round. Whereas candidates who cleared


the Cognitive Ability and Technical Round must take this round. This is an
Elimination round and the Score of this round will be considered at the final
Interview.
Second Assessment
Accenture Communication Assessment Round is not an elimination round.
Candidates will be tested in the parameters like Sentence Mastery, Vocabulary,
Fluency, and Pronunciation.

Section Duration of Time

Communication Assessment 20 min

Career Options for Python in Accenture


Accenture works on a variety of initiatives with more than 91 Fortune-100
worldwide companies. It looks for the top applicants who can meet its ideal
qualifications and uphold its key principles. As a result, the organisation designs
an intense Accenture interview process in order to choose the best applicants
from the massive pool of submissions.
 By continuously providing value and being relevant and responsive, you
may help clients become high performers and build lasting connections.

68
 To give clients outstanding support in their business endeavours, take
advantage of global insight, collaboration, and learning.
 Courtesy towards the individual: Recognise individual contributions,
cultivate a transparent and reliable atmosphere, and conduct yourself in a
way that aligns with the company’s principles.
 Draw in and keep the greatest candidates by introducing fresh challenges
that will broaden workers’ horizons and cultivate a team-oriented,
encouraging atmosphere.
 Integrity is the quality of being truthful, fostering trust by keeping your
word, and accepting full accountability for your actions.
 Uphold your duty to better communities and the environment throughout
the world, satisfy your commitments to stakeholders, and build the
company for future generations.

Interview Question And Answers


Beginner Level
In this section, we cover the basics of Python, which is ideal for those just
starting their programming journey. You'll explore:
 Basic Syntax: Understand Python's simple and intuitive syntax.
 Data Types: Understand integers, strings, lists, and more.
 Basic Operations: Learn arithmetic operations, string manipulations, and
list handling.
 Control Structures: Master loops, conditionals, and basic flow control.
 Simple Functions: Start writing your functions to organize and reuse
code.
This level builds a strong foundation, ensuring you're well-prepared to move on
to more advanced topics.
1. What is Python?
Python is an interpreted, high-level, general-purpose programming language. It
emphasizes code readability with its use of significant indentation. Python
supports multiple programming paradigms, including structured (particularly
procedural), object-oriented, and functional programming.

69
2. How is Python interpreted?
Python code is executed line by line at runtime. Python internally converts the
source code into an intermediate form called bytecode, which is then executed
by the Python virtual machine (PVM).

3. What are Python's key features?


 Easy to learn and use
 Interpreted language
 Dynamically typed
 Extensive libraries
 Object-oriented
 Portable

4. What is PEP 8?
PEP 8 is the Python Enhancement Proposal that provides guidelines and best
practices for writing Python code. It covers various aspects such as naming
conventions, code layout, and indentation.

5. How do you manage memory in Python?


Python uses automatic memory management and a garbage collector to handle
memory. The garbage collector recycles memory when objects are no longer in
use.

6. What are Python's data types?


 Numeric types: int, float, complex
 Sequence types: list, tuple, range

70
 Text type: str
 Set types: set, frozenset
 Mapping type: dict
 Boolean type: bool
 Binary types: bytes, bytearray, memoryview

7. What is the difference between a list and a tuple?


 List: Mutable, can be changed after creation.
 Tuple: Immutable, cannot be changed after creation.

8. How do you handle exceptions in Python?


Using the try-except block:
try:
# code that may raise an exception
except SomeException as e:
# code to handle the exception

9. Converting an Integer into Decimals


import decimal
integer = 10
print([Link](integer))
print(type([Link](integer)))

> 10
> <class '[Link]'>

10. Converting a String of Integers into Decimals

71
import decimal
string = '12345'
print([Link](string))
print(type([Link](string)))

> 12345
> <class '[Link]'>

11. Reversing a String using an Extended Slicing Technique


string = "Python Programming"
print(string[::-1])

> gnimmargorP nohtyP

12. Counting Vowels in a Given Word


vowel = ['a', 'e', 'i', 'o', 'u']
word = "programming"
count = 0
for character in word:
if character in vowel:
count += 1
print(count)

>3

13. Counting Consonants in a Given Word


vowel = ['a', 'e', 'i', 'o', 'u']

72
word = "programming"
count = 0
for character in word:
if character not in vowel:
count += 1
print(count)

>8

14. Counting the Number of Occurrences of a Character in a String


word = "python"
character = "p"
count = 0
for letter in word:
if letter == character:
count += 1
print(count)

>1

15. Writing Fibonacci Series


fib = [0,1]
# Range starts from 0 by default
for i in range(5):
[Link](fib[-1] + fib[-2])

# Converting the list of integers to string

73
print(', '.join(str(e) for e in fib))

> 0, 1, 1, 2, 3, 5, 8

16. Finding the Maximum Number in a List


numberList = [15, 85, 35, 89, 125]

maxNum = numberList[0]
for num in numberList:
if maxNum < num:
maxNum = num
print(maxNum)

> 125

17. Finding the Minimum Number in a List


numberList = [15, 85, 35, 89, 125, 2]

minNum = numberList[0]
for num in numberList:
if minNum > num:
minNum = num
print(minNum)

>2

18. Finding the Middle Element in a List

74
numList = [1, 2, 3, 4, 5]
midElement = int((len(numList)/2))

print(numList[midElement])

>3

19. Converting a List into a String


lst = ["P", "Y", "T", "H", "O", "N"]
string = ''.join(lst)

print(string)
print(type(string))

> PYTHON
> <class 'str'>

20. Adding Two List Elements Together


lst1 = [1, 2, 3]
lst2 = [4, 5, 6]

res_lst = []
for i in range(0, len(lst1)):
res_lst.append(lst1[i] + lst2[i])
print(res_lst)

> [5, 7, 9]

75
Another approach
a = [1, 2, 3]
b = [4, 5, 6]

c = [x + y for x, y in zip(a, b)]


print(c)

> [5, 7, 9]

21. Comparing Two Strings for Anagrams


str1 = "Listen"
str2 = "Silent"

str1 = list([Link]())
str2 = list([Link]())
[Link](), [Link]()

if(str1 == str2):
print("True")
else:
print("False")

> True
22. Checking for Palindrome Using Extended Slicing Technique
str1 = "Kayak".lower()
str2 = "kayak".lower()

76
if(str1 == str2[::-1]):
print("True")
else:
print("False")

> True

23. Counting the White Spaces in a String


string = "P r ogramm in g "
print([Link](' '))

>5

24. Counting Digits, Letters, and Spaces in a String


# Importing Regular Expressions Library
import re

name = 'Python is 1'

digitCount = [Link]("[^0-9]", "", name)


letterCount = [Link]("[^a-zA-Z]", "", name)
spaceCount = [Link]("[ \n]", name)

print(len(digitCount))
print(len(letterCount))
print(len(spaceCount))

77
>1
>8
>2

25. Counting Special Characters in a String


# Importing Regular Expressions Library
import re
spChar = "!@#$%^&*()"

count = [Link]('[\w]+', '', spChar)


print(len(count))

> 10

26. Removing All Whitespace in a String


import re

string = "C O D E"


spaces = [Link](r'\s+')
result = [Link](spaces, '', string)
print(result)

> CODE

27. Building a Pyramid in Python


floors = 3

78
h = 2*floors-1
for i in range(1, 2*floors, 2):
print('{:^{}}'.format('*'*i, h))

> *
***
*****

28. Randomizing the Items of a List in Python


from random import shuffle

lst = ['Python', 'is', 'Easy']


shuffle(lst)
print(lst)

> ['Easy', 'is', 'Python']

29. Find the Largest Element in a List


def find_largest_element(lst):
return max(lst)

# Example usage:
print(find_largest_element([1, 2, 3, 4, 5]))

>5

30. Remove Duplicates from a List

79
def remove_duplicates(lst):
return list(set(lst))

# Example usage:
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))

> [1, 2, 3, 4, 5]

31. Factorial of a Number


def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

# Example usage:
print(factorial(5))

> 120

32. Merge Two Sorted Lists


def merge_sorted_lists(lst1, lst2):
return sorted(lst1 + lst2)

# Example usage:
print(merge_sorted_lists([1, 3, 5], [2, 4, 6]))

> [1, 2, 3, 4, 5, 6]

80
33. Find the First Non-Repeating Character
def first_non_repeating_character(s):
for i in s:
if [Link](i) == 1:
return i
return None

# Example usage:
print(first_non_repeating_character("swiss"))

>w

Advanced Level
In this section, we dive into more complex Python topics, aimed at those
looking to deepen their expertise. You’ll tackle:
 Advanced Data Structures: Work with sets, tuples, and more complex
data types.
 Recursion and Iteration: Solve problems using advanced looping and
recursive techniques.
 Algorithms: Explore sorting, searching, and optimization algorithms in
depth.
 Modules and Libraries: Leverage powerful Python libraries for various
applications.
 Error Handling and Debugging: Learn to write robust code with effective
error handling and debugging techniques.
 Web Scraping and APIs: Gain experience in extracting data from websites
and interacting with APIs.
 Advanced Object-Oriented Programming (OOP): Master OOP concepts
like inheritance, polymorphism, and design patterns.

81
This level will challenge you to think critically and apply your knowledge to
complex problems, preparing you for high-level Python applications and
interviews.
34. What are Python metaclasses?
Metaclasses are classes of classes that define how classes behave. A class is an
instance of a metaclass. They allow customization of class creation.

35. Explain the difference between is and ==.


is: Checks if two references point to the same object.
==: Checks if the values of two objects are equal.

36. How does Python's memory management work?


Python uses reference counting and garbage collection. Objects with a reference
count of zero are automatically cleaned up by the garbage collector.

37. What is the purpose of Python's with statement?


The with statement simplifies exception handling by encapsulating common
preparation and cleanup tasks in so-called context managers.
with open('[Link]', 'r') as file:
data = [Link]()

38. What are Python's @staticmethod and @classmethod?


@staticmethod: Defines a method that does not operate on an instance or class;
no access to self or cls.
@classmethod: Defines a method that operates on the class itself; it receives the
class as an implicit first argument (cls).

39. How do you implement a singleton pattern in Python?


Using a metaclass

82
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]

class MyClass(metaclass=Singleton):
pass

40. Explain Python's garbage collection mechanism


Python uses a garbage collection mechanism based on reference counting and a
cyclic garbage collector to detect and collect cycles (groups of objects that
reference each other but are not accessible from any other object).

41. What are Python's magic methods?


Magic methods (or dunder methods) are special methods with double
underscores at the beginning and end. They enable the customization of
behavior for standard operations
 __init__: Constructor
 __str__: String representation
 __add__: Addition operator

42. How do you handle multi-threading in Python?


Using the threading module:
import threading

def print_numbers():

83
for i in range(10):
print(i)

thread = [Link](target=print_numbers)
[Link]()
[Link]()

43. What are Python's coroutine functions?


Coroutines are a type of function that can pause and resume their execution.
They are defined with async def and use await to yield control back to the event
loop.
import asyncio

async def say_hello():


await [Link](1)
print("Hello")

[Link](say_hello())

44. Explain Python's Global Interpreter Lock (GIL). How does it affect
multithreading?
The Global Interpreter Lock (GIL) is a mutex that protects access to Python
objects, preventing multiple native threads from executing Python bytecodes
simultaneously in CPython. This lock simplifies memory management and
ensures thread safety, but it limits the performance of multi-threaded Python
programs by allowing only one thread to execute at a time. As a result, Python
multithreading is more suitable for I/O-bound tasks than CPU-bound tasks.
Multiprocessing or other Python implementations, like Jython or IronPython,
may be preferred for CPU-bound tasks.

84
45. What are metaclasses in Python, and how are they used?
A metaclass in Python is a class of a class that defines how a class behaves.
Classes themselves are instances of metaclasses. You can customize class
creation by defining a metaclass, such as modifying class properties, adding
methods, or implementing design patterns. A common use case for metaclasses
is enforcing coding standards or design patterns, such as singleton, or auto-
registering classes.

46. Can you explain the difference between deepcopy and copy in Python?
The copy module in Python provides two methods: copy() and deepcopy().
 [Link]() creates a shallow copy of an object. It copies the object's
structure but not the elements themselves, meaning it only copies
references for mutable objects.
 [Link]() creates a deep copy of the object, including recursively
copying all objects contained within the original object. Changes made to
the deep-copied object do not affect the original object.

47. Describe Python’s __slots__ and its benefits.


__slots__ is a special attribute in Python that allows you to explicitly declare
data members (slots) and prevent the creation of __dict__, thereby reducing
memory overhead. By using __slots__, you can limit the attributes of a class to
a fixed set of fields and reduce the per-instance memory consumption. This is
particularly beneficial when creating a large number of instances of a class.

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


 is checks for identity, meaning it returns True if two references point to
the same object in memory.
 == checks for equality, meaning it returns True if the values of the objects
are equal, even if they are different objects in memory.
a = [1, 2, 3]
b=a
c = [1, 2, 3]

85
print(a is b) # True, because both a and b refer to the same object
print(a is c) # False, because a and c refer to different objects
print(a == c) # True, because a and c have the same values
49. Find the Longest Consecutive Sequence in an Unsorted List
Problem: Given an unsorted list of integers, find the length of the longest
consecutive sequence.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4 # (Sequence: [1, 2, 3, 4])
Solution:
def longest_consecutive(nums):
num_set = set(nums) # Convert list to set for O(1) lookups
longest = 0

for num in num_set:


if num - 1 not in num_set: # Start of a new sequence
length = 1
while num + length in num_set:
length += 1
longest = max(longest, length)

return longest

# Example usage:
print(longest_consecutive([100, 4, 200, 1, 3, 2])) # Output: 4
Complexity: O(N), where N is the number of elements.

86
Most Frequently Asked Python Questions by Big Tech Companies
As we gear up for technical interviews, it’s essential to be prepared for the
toughest Python questions. If you're preparing for high-level technical
interviews, you'll want to master these complex Python problems. Here’s a list
of coding questions that have been asked by top-tier companies!

1. Longest Substring Without Repeating Characters


Problem
Given a string, find the length of the longest substring without repeating
characters.
def length_of_longest_substring(s: str) -> int:
char_set = set()
left = 0
max_len = 0

for right in range(len(s)):


while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_len = max(max_len, right - left + 1)

return max_len

# Example usage
print(length_of_longest_substring("abcabcbb")) # Output: 3
Explanation
Sliding window approach with a set to track unique characters.
Asked by: Meta (Phone Interview, 2022) — Source: LeetCode Discuss

87
2. Merge Intervals
Problem
Merge overlapping intervals in a list.
from typing import List

def merge(intervals: List[List[int]]) -> List[List[int]]:


if not intervals:
return []

[Link](key=lambda x: x[0])
merged = [intervals[0]]

for current in intervals[1:]:


prev = merged[-1]
if current[0] <= prev[1]:
prev[1] = max(prev[1], current[1])
else:
[Link](current)

return merged

# Example usage
print(merge([[1,3],[2,6],[8,10],[15,18]])) # Output: [[1,6],[8,10],[15,18]]
Explanation
Sort intervals and merge overlapping ones.
Asked by: Google (Onsite Interview, 2021) — Source: GeeksforGeeks

88
3. Two Sum
Problem
Return indices of two numbers that add up to a target.
def two_sum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
return []

# Example usage
print(two_sum([2, 7, 11, 15], 9)) # Output: [0, 1]
Explanation
Hashmap tracks complements during traversal.
Asked by: Amazon (OA, 2023) — Source: LeetCode Discuss

4. Group Anagrams
Problem
Group words that are anagrams.
from collections import defaultdict

def group_anagrams(strs):
anagram_map = defaultdict(list)
for word in strs:
sorted_word = ''.join(sorted(word))
anagram_map[sorted_word].append(word)

89
return list(anagram_map.values())

# Example usage
print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
Explanation
Sorted word acts as key in a hashmap.
Asked by: Microsoft (Interview, 2022) — Source: LeetCode Premium

5. Valid Parentheses
Problem
Determine if a string has valid parentheses.
def is_valid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in [Link]():
[Link](char)
elif char in mapping:
if not stack or stack[-1] != mapping[char]:
return False
[Link]()
else:
return False
return not stack

# Example usage
print(is_valid("()[]{}")) # Output: True

90
Explanation
Stack checks for balanced brackets.
Asked by: Apple (Onsite, 2021) — Source: Glassdoor

6. Top K Frequent Elements


from collections import Counter
import heapq

def top_k_frequent(nums, k):


count = Counter(nums)
return [Link](k, [Link](), key=[Link])

# Example usage
print(top_k_frequent([1,1,1,2,2,3], 2)) # Output: [1, 2]
Asked by: Google (2022) — Source: LeetCode Discuss

7. Product of Array Except Self


def product_except_self(nums):
res = [1] * len(nums)
prefix = 1
for i in range(len(nums)):
res[i] = prefix
prefix *= nums[i]

suffix = 1
for i in reversed(range(len(nums))):
res[i] *= suffix
suffix *= nums[i]

91
return res

# Example usage
print(product_except_self([1,2,3,4])) # Output: [24,12,8,6]
Asked by: Amazon (SDE-2, 2023) — Source: LeetCode

8. Binary Tree Level Order Traversal


from collections import deque

def level_order(root):
if not root:
return []
res = []
queue = deque([root])
while queue:
level = []
for _ in range(len(queue)):
node = [Link]()
[Link]([Link])
if [Link]: [Link]([Link])
if [Link]: [Link]([Link])
[Link](level)
return res
Asked by: Facebook (2022) — Source: Glassdoor

9. Rotate Image (Matrix)

92
def rotate(matrix):
[Link]()
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
Asked by: Google (2021) — Source: LeetCode

10. Search in Rotated Sorted Array


def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1

93
Part-II
1. What is Python?
Answer: Python is a high-level, interpreted programming language known for
its readability, simplicity, and versatility. It supports multiple programming
paradigms including procedural, object-oriented, and functional programming.

94
Explanation: Python is widely used in web development, data science, AI,
automation, and scripting due to its easy syntax and strong community support.

2. What are Python's key features?


 Easy to learn and use
 Interpreted language
 Dynamically typed
 Open source
 Extensive standard library
 Supports multiple paradigms (OOP, functional, procedural)
 Large community support
Explanation: These features make Python suitable for both beginners and
professional developers.

3. What is PEP 8?
Answer: PEP 8 is Python's official style guide that provides coding conventions
for writing readable and consistent Python code.
Explanation: Following PEP 8 ensures your code is clean, maintainable, and
adheres to community standards.

4. 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 Limited Default

End of life 2020 Supported

95
Explanation: Python 3 is the current standard. Python 2 is outdated and not
recommended for new projects.

5. What are Python data types?


 Numeric: int, float, complex
 Sequence: list, tuple, range
 Text: str
 Set types: set, frozenset
 Mapping: dict
 Boolean: bool
 None type: NoneType
Explanation: Data types define the kind of value a variable can hold.

6. What is the difference between list, tuple, and set?

Feature List Tuple Set

Mutable Yes No Yes

Ordered Yes Yes No

Duplicate Allowed Allowed Not allowed

Explanation: Use tuples for immutable sequences, sets for unique items, and
lists for flexible collections.

7. What is a Python dictionary?


Answer: A dictionary is a collection of key-value pairs enclosed in {}. Each
key is unique.
Example:
person = {"name": "Alice", "age": 25}
print(person["name"]) # Output: Alice

96
Explanation: Dictionaries are ideal for fast lookups using unique keys.

8. What are Python functions?


Answer: Functions are reusable blocks of code that perform a specific task.
Example:
def greet(name):
return f"Hello, {name}"
Explanation: Functions help organize code and avoid repetition.

9. What are Python decorators?


Answer: Decorators are functions that modify the behavior of another function
without changing its code.
Example:
def decorator(func):
def wrapper():
print("Before function")
func()
return wrapper

@decorator
def say_hello():
print("Hello")

say_hello()
Explanation: Decorators are used for logging, access control, and
instrumentation.

10. What is Python's *args and **kwargs?

97
 *args allows passing a variable number of positional arguments.
 **kwargs allows passing a variable number of keyword arguments.
Example:
def func(*args, **kwargs):
print(args, kwargs)
Explanation: Useful for flexible function signatures.

11. What is the difference between shallow copy and deep copy?
 Shallow copy: Copies only the reference to the objects, changes affect the
original.
 Deep copy: Creates a new object and recursively copies all objects.
Example:
import copy
list1 = [[1, 2], [3, 4]]
shallow = [Link](list1)
deep = [Link](list1)

12. What are Python modules and packages?


 Module: A file containing Python code (.py).
 Package: A folder containing modules and __init__.py.
Explanation: They help organize code into reusable and maintainable units.

13. What is Python's Global Interpreter Lock (GIL)?


Answer: GIL is a mutex that allows only one thread to execute Python bytecode
at a time.
Explanation: It affects multithreaded CPU-bound tasks, but not I/O-bound
tasks.

98
14. What is the difference between Python multithreading and
multiprocessing?

Feature Multithreading Multiprocessing

Parallelism Limited (GIL) True parallelism

Memory Shared memory Separate memory

Use case I/O-bound tasks CPU-bound tasks

15. What is Python's with statement?


Answer: with is used to simplify resource management (e.g., file handling) and
ensures proper cleanup.
Example:
with open("[Link]") as f:
data = [Link]()

16. What are Python iterators and generators?


 Iterator: Object that can be iterated using __iter__() and __next__().
 Generator: Function that yields values lazily using yield.
Example:
def gen():
for i in range(3):
yield i

17. What is the difference between is and ==?


 is: Checks identity (if two objects are the same in memory)
 ==: Checks value equality
Example:

99
a = [1,2]; b = [1,2]
print(a == b) # True
print(a is b) # False

18. What is Python's lambda function?


Answer: Anonymous inline function using lambda keyword.
Example:
square = lambda x: x*x
print(square(5)) # 25
Explanation: Useful for short, throwaway functions.

19. What is exception handling in Python?


Answer: Mechanism to handle runtime errors using try, except, finally.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

20. What are Python's built-in data structures?


 Lists
 Tuples
 Sets
 Dictionaries
 Strings
Explanation: Built-in data structures are optimized for different use cases, such
as sequences, mappings, and sets.

100
Author: Tanu Nanda Prabhu
Last Updated: August 17, 2025
Part – III
Accenture HR Interview Questions
1. Why do you want to work at Accenture?
As the tagline of Accenture says, “Let There Be Change,” I wish to be a part of
the change and contribute to its growth. I’m excited about the chance to learn
and contribute to a company that values innovation and is always looking to
improve. In addition, there are opportunities to learn and grow. Accenture
values diversity and teamwork. I feel I could thrive in the innovative culture and
would enjoy being part of this respected organization.
2. How do you handle stressful situations or deadlines?
When faced with stress or tight deadlines, I stay calm and focused. I prioritize
the most important tasks and break them into smaller steps. I communicate
openly with my team and manager if I need support, and I don’t procrastinate.
Staying organized and proactive and asking for help when needed allows me to
handle challenges smoothly.
3. What are your strengths and weaknesses?
Try to focus on strengths that mainly align with the job requirements rather than
trying to present all the skills that you have. Try to mention a weakness that is
correctable and won’t affect your core responsibilities on the job. Don’t
jeopardize your job by mentioning your weakness.
My strengths are that I work very hard, learn quickly, and solve problems
creatively. I also work well both independently and as part of a team. A
weakness is that sometimes I take on too many tasks at once and need to
improve at managing my time effectively.
4. How do you handle conflicts in a team?
If a conflict arises in my team, I try to stay calm and listen to understand each
perspective. My approach is to find common goals and bring people together to
find a solution where everyone feels heard. Communication and compromise
are key to resolving issues and keeping the team working well together.
5. Where do you see yourself in the next five years?

101
In five years, I hope to be in a leadership role in this company where I can use
my skills and experience to mentor others. I would like to take on more
responsibility and help my team succeed in their work. I also aim to
continuously learn new skills and expand my expertise through ongoing
training.
6. What motivates you?
I am motivated by the opportunity to solve challenging problems, learn new
things, and see the impact of my work. Knowing that I am helping others and
contributing to the success of my team and company also drives me forward.
7. How do you stay updated with industry trends?
To stay current with industry trends, I regularly read journals and write reports
in my free time. I also follow leaders in my field on social media and
networking sites to learn about new developments. Taking online courses
further expands my knowledge of emerging topics and technologies.
8. Tell me about a challenging situation at work and how you handled it.
One difficult time was when a big project fell behind. I worked with my
manager to prioritize tasks and asked others for help. By delegating well and
focusing on the most important parts first, we got it back on track.
Communication and teamwork helped solve the problem.
9. How do you handle constructive criticism?
I welcome constructive criticism as an opportunity to improve. Rather than get
defensive, I actively listen to understand different points of view. I then reflect
on the feedback and work to apply it productively.
10. What skills and experiences do you bring to the table? / Share with me
your professional background and expertise.
I have strong skills in project management, communication, and problem-
solving from my past roles. As a project coordinator, I handled complex tasks
and budgets. My background in customer service also developed my ability to
build relationships and work well with others.
Accenture Interview Questions for Freshers
11. Difference between procedural and object-oriented programming
In procedural programming, we need to work with functions and data
separately, as functions manipulate data that is stored in variables or data

102
structures, whereas in an object-oriented programming language, the code is
treated as entities and objects.

12. What is the importance of self-keywords in Python?


The ‘self’ keyword is used as the first parameter while defining the instance
methods of a class. In other words, we can say it represents the instance of the
class itself. Although the name self is a convention, we can technically use any
name as the first parameter, but using self is considered standard and is used in
Python.
13. What is the difference between static and non-static keywords?
In static, you do not need an instance to use a static method. It is independent of
any specific object but related to the entire class. It is stored in a single memory
location and can be modified by any instance of the class. A non-static method
is an instance method that is not independent but belongs to each object that is
generated from the class.
14. Why is Python known as a high-level language?
python is a high-level language because it is an easy and user-friendly way to
write and read code. It doesn’t have that much critical syntax. It hides
complexity, making programming more accessible and less focused on low-
level operations.
15. Define the adapter class.
An adapter class is defined as a class that helps two incompatible classes
combine by providing a single interface. It acts as a mediator, which allows
objects with different interfaces to communicate.
16. What is run-time polymorphism?
Run-time polymorphism helps us to allow different objects to be treated as
objects of a common super-class while executing different implementations of a
method based on the actual type of the object at runtime. It also allows us to use
the same method with different signature names.
17. What is the difference between Python and Java?
Java & python are both programming languages, but they are different from
each other. In Python, we can simply use “print” to print something, whereas in
Java, we use [Link].

103
18. What is NumPy in Python?
NumPy stands for Numerical python, and it is a library used for scientific
computing, data analysis, and numerical operations. Some common use cases
and applications of NumPy are mathematical operations, data analysis, and
machine learning.
19. What do you mean by name mangling in Python?
The purpose of name mangling is to make the attribute private and prevent
direct access from outside the class. It is a method that indicates that the
attribute is bound for internal use within the class and cannot be achieved or
modified with external code.

SOURCE LINKS:
[Link]
[Link]

104
[Link]
Prabhu/Python/blob/master/Python%20Coding%20Interview%20Prep/Python_I
nterview_Questions_and_Answers.md
[Link]
[Link]
[Link]

105

You might also like