Data Structures in Python Guide
Data Structures in Python Guide
COGNIZANT
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.
print("Hello, World!")
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")
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.
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)
6
print("Number of girls: ", y)
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
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")
# 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
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
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
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)
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
# 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
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
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
Keywords Identifiers
30
Keywords Identifiers
Variables Keywords
Hold values that are manipulated in the Used to define the structure of
program. Python code.
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)
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 = []
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])
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 = ()
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])
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)
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 = {}
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'}
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
If
Statement
Example:
age = 20
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
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
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
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
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':
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
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:
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")
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)
Output
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments
def myFun(**kwargs):
for key, value in [Link]():
print("%s == %s" % (key, value))
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
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
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]
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.
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
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.
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).
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.
70
Text type: str
Set types: set, frozenset
Mapping type: dict
Boolean type: bool
Binary types: bytes, bytearray, memoryview
> 10
> <class '[Link]'>
71
import decimal
string = '12345'
print([Link](string))
print(type([Link](string)))
> 12345
> <class '[Link]'>
>3
72
word = "programming"
count = 0
for character in word:
if character not in vowel:
count += 1
print(count)
>8
>1
73
print(', '.join(str(e) for e in fib))
> 0, 1, 1, 2, 3, 5, 8
maxNum = numberList[0]
for num in numberList:
if maxNum < num:
maxNum = num
print(maxNum)
> 125
minNum = numberList[0]
for num in numberList:
if minNum > num:
minNum = num
print(minNum)
>2
74
numList = [1, 2, 3, 4, 5]
midElement = int((len(numList)/2))
print(numList[midElement])
>3
print(string)
print(type(string))
> PYTHON
> <class 'str'>
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]
> [5, 7, 9]
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
>5
print(len(digitCount))
print(len(letterCount))
print(len(spaceCount))
77
>1
>8
>2
> 10
> CODE
78
h = 2*floors-1
for i in range(1, 2*floors, 2):
print('{:^{}}'.format('*'*i, h))
> *
***
*****
# Example usage:
print(find_largest_element([1, 2, 3, 4, 5]))
>5
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]
# Example usage:
print(factorial(5))
> 120
# 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.
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
def print_numbers():
83
for i in range(10):
print(i)
thread = [Link](target=print_numbers)
[Link]()
[Link]()
[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.
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
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!
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
[Link](key=lambda x: x[0])
merged = [intervals[0]]
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
# Example usage
print(top_k_frequent([1,1,1,2,2,3], 2)) # Output: [1, 2]
Asked by: Google (2022) — Source: LeetCode Discuss
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
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
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
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.
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.
95
Explanation: Python 3 is the current standard. Python 2 is outdated and not
recommended for new projects.
Explanation: Use tuples for immutable sequences, sets for unique items, and
lists for flexible collections.
96
Explanation: Dictionaries are ideal for fast lookups using unique keys.
@decorator
def say_hello():
print("Hello")
say_hello()
Explanation: Decorators are used for logging, access control, and
instrumentation.
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)
98
14. What is the difference between Python multithreading and
multiprocessing?
99
a = [1,2]; b = [1,2]
print(a == b) # True
print(a is b) # False
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.
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