1
1. How will you extract a single character from string with example?
In Python, a string is a sequence of characters enclosed within single quotes (' '), double
quotes (" "), or triple quotes (''' ''' or """ """). Strings are one of the most commonly used
data types in Python, and they are mainly used to store and manipulate textual data.
A string is treated as an ordered collection of characters, where each character has a
specific index position. Indexing in Python starts from 0 for the first character, increases by 1
for each next character, and goes up to n-1, where n is the length of the string. Python also
supports negative indexing, where the last character has index -1, the second last has -2,
and so on.
One important property of strings in Python is that they are immutable, which means the
characters in a string cannot be changed once the string is created. However, individual
characters can be extracted (accessed) for reading and processing. To extract a single
character, we use the indexing operator [ ] with either a positive or negative index value.
Example:
text = "PYTHON"
# Extracting using positive indexing
print(text[0])
Output:
P (first character)
print(text[3])
Output:
H (fourth character)
# Extracting using negative indexing
print(text[-1])
Output:
N (last character)
2
print(text[-3])
Output:
H (third last character)
Thus, strings in Python are sequences of characters, and individual characters can be
extracted easily using positive or negative indexing, even though the string itself cannot be
modified.
2. How can you modify individual items of the list?
In Python, lists are mutable, which means the elements of a list can be modified after the list
is created. To change an individual item, we use the index position of that element and
assign a new value to it. Indexing starts from 0, so the first element has index 0, the second
element has index 1, and so on. Modification can also be done for a group of elements using
list slicing. This feature makes lists more flexible compared to immutable data types like
strings and tuples.
Example:
# Example of modifying individual items in a list
numbers = [10, 20, 30, 40, 50]
# Changing a single element using index
numbers[2] = 99 # changes the third element
print(numbers)
Output:
[10, 20, 99, 40, 50]
# Modifying multiple elements using slicing
numbers[1:3] = [111, 222]
print(numbers)
Output:
3
[10, 111, 222, 40, 50]
Thus, individual items (or a slice of items) in a list can be easily modified using indexing and
assignment.
3. Explain about sets in python?
A set in Python is a built-in data type that represents an unordered collection of unique and
immutable elements. Sets are widely used when we want to store data without duplicates
and perform mathematical set operations like union, intersection, and difference.
1. Creation of Sets
Sets can be created by placing elements inside curly braces { }, separated by commas.
Alternatively, we can use the set() constructor to create a set.
Empty curly braces { } will create an empty dictionary, so an empty set must be
created using set().
Example:
# Creating sets
s1 = {1, 2, 3, 4}
s2 = set([2, 3, 4, 5])
print(s1) # Output: {1, 2, 3, 4}
print(s2) # Output: {2, 3, 4, 5}
2. Properties of Sets
1. Unordered – The elements in a set do not have a defined order.
2. Unique – Duplicate values are automatically removed.
3. Mutable container – We can add or remove elements after creation.
4. Immutable elements only – Elements inside a set must be of immutable types like
numbers, strings, or tuples. Lists and dictionaries cannot be added to sets.
4
5. No indexing/slicing – Since sets are unordered, elements cannot be accessed using
index positions like lists or tuples.
3. Adding and Removing Elements
add() → adds a single element.
update() → adds multiple elements (from list, tuple, or another set).
remove() → removes an element (throws error if not found).
discard() → removes an element (no error if not found).
pop() → removes and returns a random element.
clear() → removes all elements.
Example:
s = {10, 20, 30}
[Link](40) # {10, 20, 30, 40}
[Link]([50, 60]) # {10, 20, 30, 40, 50, 60}
[Link](20) # {10, 30, 40, 50, 60}
[Link](100) # No error even if element not found
4. Set Operations
Python provides operators and methods for performing mathematical set operations:
1. Union (| or union()) → combines elements from both sets.
2. Intersection (& or intersection()) → common elements of both sets.
3. Difference (- or difference()) → elements present in one set but not in another.
4. Symmetric Difference (^ or symmetric_difference()) → elements present in either
set, but not in both.
5. Subset and Superset
o [Link](B) → True if all elements of A are in B.
5
o [Link](B) → True if A contains all elements of B.
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # Union → {1, 2, 3, 4, 5, 6}
print(A & B) # Intersection → {3, 4}
print(A - B) # Difference → {1, 2}
print(A ^ B) # Symmetric Difference → {1, 2, 5, 6}
5. Frozen Sets
Python also provides frozenset, which is an immutable version of a set.
Once created, elements cannot be added or removed.
Useful when we want a set as a dictionary key or as an element of another set.
Example:
fset = frozenset([1, 2, 3])
# [Link](4) ❌ Error (immutable)
print(fset) # Output: frozenset({1, 2, 3})
6. Applications of Sets
Removing duplicate values from a list.
Performing mathematical set operations (union, intersection, etc.).
Fast membership testing using in.
Useful in data science, algorithms, and situations where order doesn’t matter but
uniqueness does.
Conclusion
6
Sets in Python are unordered, mutable collections of unique elements that support
powerful mathematical operations. They help in eliminating duplicates, performing fast
membership tests, and handling problems where uniqueness is important. For cases where
immutability is required, Python provides frozenset.
4. Which operator is used to check the membership in dictionary explain with example?
A dictionary in Python is a collection of key–value pairs, where each key must be unique and
immutable, while the values can be of any data type. It is one of the most important data
structures used for fast lookups, storing, and accessing data.
In many situations, we need to check whether a particular key or value exists in the
dictionary. Python provides two membership operators for this purpose:
1. in Operator
o Returns True if the specified key is present in the dictionary.
o By default, membership checking in a dictionary applies only to the keys, not
the values.
2. not in Operator
o Returns True if the specified key is not present in the dictionary.
Important Note
Membership operators directly test the keys of the dictionary.
To test whether a value exists, we must use the .values() method.
Similarly, to test whether a (key, value) pair exists, we can use the .items() method.
Example:
# Creating a dictionary
student = {
"name": "Anu",
"age": 22,
7
"course": "MCF"
# Checking membership in keys
print("name" in student) # True (key exists)
print("rollno" in student) # False (key does not exist)
# Checking membership using 'not in'
print("rollno" not in student) # True
# Checking membership in values
print("Anu" in [Link]()) # True
print(25 in [Link]()) # False
# Checking membership in items
print(("age", 22) in [Link]()) # True
Output:
True
False
True
True
False
True
Applications
Checking if a key exists before accessing it to avoid errors.
Validating data stored in dictionaries.
Searching for values using .values() or for key-value pairs using .items().
8
Conclusion
The in and not in operators are used for membership testing in dictionaries. By default, they
test only for the presence of keys, since dictionary keys provide fast lookups. However, with
the help of .values() and .items(), membership can also be checked for values and key–value
pairs.
5. Describe about variables and arithmetic expression in python illustrate with example?
Python is a high-level, interpreted programming language that is widely used for general-
purpose programming. Like any other language, Python makes use of variables to store data
and arithmetic expressions to perform calculations. Both of these are fundamental building
blocks of Python programming and form the basis for writing logical programs.
2. Variables in Python
Definition
A variable is a name that refers to a value stored in the memory. In Python, variables act as
symbolic names for objects. Unlike many other programming languages, Python does not
require explicit declaration of variables; they are created automatically when a value is
assigned.
Characteristics of Variables
1. Dynamic Typing → Python is dynamically typed, which means a variable can refer to
a value of any type and can be reassigned to another type at runtime.
2. x = 10 # integer
3. x = "Ajay" # string (type changed)
4. No Declaration Needed → Variables are created at the time of assignment.
5. Case-Sensitive → Variable names are case-sensitive (age and Age are different).
6. Scope → Variables may have local or global scope depending on where they are
defined.
7. Reference Based → Variables in Python are references (or pointers) to objects stored
in memory, not direct memory addresses.
9
Rules for Naming Variables
Must begin with a letter or an underscore _.
Cannot start with a digit.
Can contain letters, digits, and underscores.
Cannot use reserved words (keywords like if, for, class).
Examples
name = "John"
age = 25
height = 5.9
print("Name:", name)
print("Age:", age)
print("Height:", height)
3. Arithmetic Expressions in Python
Definition
An arithmetic expression is a combination of operands (variables or values) and operators
that are evaluated to produce a result. Python provides a rich set of arithmetic operators for
performing mathematical computations.
Arithmetic Operators
Operator Name Example Result
+ Addition 5+3 8
- Subtraction 10 - 4 6
* Multiplication 6 * 3 18
/ Division (float) 10 / 4 2.5
// Floor Division 10 // 4 2
10
Operator Name Example Result
% Modulus 10 % 4 2
** Exponentiation 2 ** 3 8
Order of Evaluation (Precedence)
Python follows the BODMAS/PEMDAS rule when evaluating expressions:
1. Parentheses
2. Exponentiation
3. Multiplication, Division, Floor division, Modulus
4. Addition and Subtraction
Example:
x = 15
y=4
print("Addition:", x + y) # 19
print("Subtraction:", x - y) # 11
print("Multiplication:", x * y) # 60
print("Division:", x / y) # 3.75
print("Floor Division:", x // y) # 3
print("Modulus:", x % y) #3
print("Power:", x ** y) # 50625
4. Combining Variables and Arithmetic Expressions
Variables can be combined with arithmetic operators to form meaningful expressions. The
results of these expressions can also be stored in variables for further use.
Example:
11
# Simple arithmetic with variables
a = 10
b=3
sum_result = a + b
diff_result = a - b
mul_result = a * b
div_result = a / b
print("Sum:", sum_result)
print("Difference:", diff_result)
print("Product:", mul_result)
print("Division:", div_result)
5. Real-Life Applications
1. Mathematical Calculations → Used in solving equations, scientific formulas, etc.
2. radius = 7
3. area = 3.14159 * radius ** 2
4. print("Area of Circle:", area)
5. Financial Calculations → Interest calculation, profit/loss computation, etc.
6. p = 10000 # principal
7. r = 5 # rate
8. t = 2 # time
9. si = (p * r * t) / 100
10. print("Simple Interest:", si)
11. Data Processing → Used in statistics, data science, and numerical computing.
12
6. Conclusion
Variables and arithmetic expressions are fundamental concepts in Python programming. A
variable serves as a symbolic name for storing data, while arithmetic expressions allow us to
perform mathematical operations using these variables. Together, they form the backbone
of most Python programs, enabling programmers to build logic, perform calculations, and
solve real-world problems efficiently.
6. Explain conditionals with example?
In Python (and in all programming languages), conditionals are used to control the flow of
execution. A program often needs to make decisions. For example:
If a student’s marks are above 50, print "Pass", otherwise print "Fail".
If a customer has enough balance, allow withdrawal, otherwise deny it.
Such decision-making is possible using conditional statements.
A conditional statement allows the program to execute a specific block of code only when a
certain condition is satisfied.
If the condition is True, the corresponding block executes.
If the condition is False, the program either skips the block or executes an alternative
block.
Boolean Expressions
At the heart of conditionals are Boolean expressions, which evaluate to either True or False.
Python uses relational operators like <, >, <=, >=, ==, and != to compare values.
It also uses logical operators like and, or, and not to combine conditions.
Example:
x = 10
y = 20
13
print(x < y) # True
print(x == y) # False
print(x > 5 and y < 30) # True
Types of Conditionals in Python
1. The if Statement
Simplest form of conditional.
Executes a block only if the condition is True.
If the condition is False, Python skips the block.
Syntax:
if condition:
statement(s)
Example:
temperature = 35
if temperature > 30:
print("It is a hot day")
Output:
It is a hot day
2. The if-else Statement
Provides two paths:
o One when the condition is True.
o Another when the condition is False.
Syntax:
if condition:
14
statement(s) if True
else:
statement(s) if False
Example:
age = 16
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
Output:
You cannot vote
3. The if-elif-else Ladder
Used when multiple conditions must be checked.
Python checks each condition from top to bottom.
As soon as a condition is True, its block runs and others are skipped.
Syntax:
if condition1:
statement(s)
elif condition2:
statement(s)
elif condition3:
statement(s)
else:
15
statement(s) if all fail
Example:
marks = 72
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Fail")
Output:
Grade: B
4. Nested if Statements
An if statement inside another if.
Useful when one decision depends on another.
Example:
number = 12
if number > 0:
if number % 2 == 0:
print("Positive Even Number")
16
else:
print("Positive Odd Number")
else:
print("Negative Number")
Output:
Positive Even Number
5. Conditional Expression (Ternary Operator)
Short-hand way of writing if-else in a single line.
Syntax:
result = value_if_true if condition else value_if_false
Example:
a, b = 15, 20
minimum = a if a < b else b
print("Minimum is:", minimum)
Output:
Minimum is: 15
Combining Conditions
Multiple conditions can be combined using logical operators:
o and → both conditions must be True.
o or → at least one condition must be True.
o not → reverses the result.
Example:
x = 25
17
if x > 10 and x < 50:
print("x is between 10 and 50")
Output:
x is between 10 and 50
Real-World Applications of Conditionals
1. Banking Systems: Checking if balance is sufficient before withdrawal.
2. Examination Systems: Assigning grades based on marks.
3. E-commerce: Giving discounts based on purchase amount.
4. Login Systems: Verifying username and password.
5. Games: Checking win/lose conditions.
Example (Discount System):
amount = 120
if amount >= 1000:
print("You get 20% discount")
elif amount >= 500:
print("You get 10% discount")
else:
print("No discount")
Conclusion
Conditionals in Python are an essential part of decision-making in programs.
They allow different code paths depending on conditions.
Python provides flexible constructs like if, if-else, if-elif-else, nested conditionals, and
ternary operators.
Using conditionals, programs become interactive, intelligent, and practical.
18
Thus, conditionals are the backbone of control flow in Python programming.
7. Explain about strings and lists with its operations?
Python is a powerful high-level programming language that provides many built-in data
types. Among them, strings and lists are two of the most commonly used. Both belong to
the category of sequence data types, which means:
They store data in a sequential (ordered) manner.
Each element can be accessed using an index.
They support operations like indexing, slicing, iteration, membership testing, and
concatenation.
Despite these similarities, there are important differences:
Strings represent text and are immutable (cannot be modified once created).
Lists represent collections of items and are mutable (can be changed after creation).
Understanding strings and lists, along with their operations, is essential for programming in
Python because they are the backbone of data handling, text processing, and collection
manipulation.
Part A: Strings in Python
Definition
A string is a sequence of Unicode characters enclosed within single quotes (' '), double
quotes (" "), or triple quotes (''' ''' or """ """).
Single and double quotes are used for single-line strings.
Triple quotes are used for multi-line strings or for documentation.
Examples:
s1 = 'Hello'
s2 = "Python"
s3 = '''This is
19
a multi-line string.'''
Characteristics of Strings
1. Sequence of characters: Each character has a unique index.
2. Immutable: Cannot be modified after creation.
3. Supports indexing and slicing.
4. Can be concatenated and repeated.
5. Rich set of built-in methods for manipulation.
Operations on Strings
1. Indexing
Access individual characters using index values.
Index starts from 0.
Negative indices start from the end.
word = "Python"
print(word[0]) # P
print(word[-1]) # n
2. Slicing
Extracts a substring by specifying a start and end index.
text = "Programming"
print(text[0:6]) # Progra
print(text[:5]) # Progr
print(text[3:]) # gramming
print(text[::2]) # Pormig
20
3. Concatenation (+)
a = "Hello"
b = "World"
print(a + " " + b) # Hello World
4. Repetition (*)
msg = "Hi! "
print(msg * 3) # Hi! Hi! Hi!
5. Membership Testing
name = "Ajay"
print("A" in name) # True
print("z" not in name) # True
6. Iteration
for ch in "Python":
print(ch)
String Methods
Python provides many built-in methods for strings:
Case Conversion
s = "hello world"
print([Link]()) # HELLO WORLD
print([Link]()) # hello world
print([Link]()) # Hello World
print([Link]()) # Hello world
21
Searching and Counting
s = "banana"
print([Link]("a")) # 3
print([Link]("na")) # 2
print([Link]("na")) # 2
Validation Methods
s = "Python123"
print([Link]()) # False
print([Link]()) # False
print([Link]()) # True
print([Link]()) # False
Splitting and Joining
msg = "one,two,three"
words = [Link](",") # ['one','two','three']
print("-".join(words)) # one-two-three
Stripping Spaces
s = " python "
print([Link]()) # "python"
Important Note on Strings
Strings are immutable. Once created, their contents cannot be changed directly.
s = "Hello"
# s[0] = "h" # ❌ Error
s = "h" + s[1:] # ✅ Creates a new string
22
print(s) # hello
Applications of Strings
1. Text processing (names, documents).
2. Natural Language Processing (NLP).
3. Data validation (checking if input is numeric, alphabetic, etc.).
4. File and database handling.
5. Web development (HTML, JSON data).
Part B: Lists in Python
Definition
A list is a collection of ordered, mutable elements enclosed within square brackets [].
Lists are versatile because they can store elements of different data types including integers,
floats, strings, and even other lists.
Example:
my_list = [10, "Python", 3.14, [1,2,3]]
Characteristics of Lists
1. Ordered collection.
2. Mutable (can be modified).
3. Can store heterogeneous data.
4. Supports nesting (lists within lists).
5. Dynamic size – can grow or shrink.
Operations on Lists
1. Indexing
lst = [10, 20, 30, 40]
23
print(lst[0]) # 10
print(lst[-1]) # 40
2. Slicing
nums = [1,2,3,4,5,6]
print(nums[1:4]) # [2,3,4]
print(nums[:3]) # [1,2,3]
print(nums[::2]) # [1,3,5]
3. Concatenation and Repetition
a = [1,2,3]
b = [4,5]
print(a + b) # [1,2,3,4,5]
print(a * 2) # [1,2,3,1,2,3]
4. Membership
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" not in fruits) # True
5. Iteration
for item in ["pen", "book", "pencil"]:
print(item)
List Methods
Adding Elements
lst = [10,20]
[Link](30) # [10,20,30]
24
[Link](1,15) # [10,15,20,30]
Removing Elements
[Link](20) # removes first 20
[Link]() # removes last element
del lst[0] # deletes element at index 0
Updating Elements
lst = [1,2,3]
lst[1] = 20
print(lst) # [1,20,3]
Sorting and Reversing
nums = [3,1,4,2]
[Link]() # [1,2,3,4]
[Link]() # [4,3,2,1]
Other Useful Methods
nums = [10,20,30,20]
print([Link](20)) # 2
print([Link](30)) # 2
Nested Lists
Lists can store other lists (used for matrices).
matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(matrix[0][1]) # 2
Applications of Lists
1. Storing collections like student records, shopping carts.
25
2. Implementing stacks and queues.
3. Representing matrices in scientific computing.
4. Data analysis (storing rows and columns).
5. Dynamic storage in real-world apps like banking, e-commerce, and AI.
Comparison Between Strings and Lists
Feature String List
Data Sequence of characters Sequence of any data type
Mutability Immutable Mutable
Enclosure Quotes (' ', " ", ''' ''') Square brackets []
Example "Python" [1, "Python", 3.14]
Nesting Not possible Possible (lists within lists)
Conclusion
Strings and lists are fundamental sequence types in Python.
Strings are designed for handling text data and are immutable.
Lists are designed for handling collections of data and are mutable.
Both support a variety of operations like indexing, slicing, concatenation, repetition,
membership, and iteration.
Python provides rich built-in methods for manipulating both strings and lists, making
programming tasks easier and more powerful.
Mastering strings and lists is essential for any Python programmer, as they are the building
blocks for solving real-world problems in text processing, data storage, analysis, and
application development.