Chapter -1 Computer Science
Question and Answer
Q1. What is a string? Give an example.
Answer :-
A string is a sequence of characters enclosed within
single quotes (' '), double quotes (" "), or
triple quotes (''' ''' or """ """) in Python.
Strings are used to store and manipulate text data such as names,
messages, addresses, and sentences.
Syntax:
string_name = "Text"
Example:
# Creating a string
name = "Hardik"
print(name)
Output:
Hardik
Explanation:
"Hardik"is a string because it is enclosed in double quotes.- The variable
namestores the string value. - The
print()function displays the string on the screen.
Q2. What is string slicing?
Answer :-
String slicing is the process of extracting a part (substring)
of a string using the slicing operator [:]. It allows us to
access a specific range of characters from a string by specifying the
starting and ending index.
Syntax:
string_name[start : stop : step]
- start – Starting index (inclusive).
- stop – Ending index (exclusive).
- step – Interval between characters (optional).
Example:
# String Slicing Example
text = "COMPUTER"
print(text[0:4])
print(text[2:6])
print(text[-4:-1])
Output:
COMP
MPUT
PUT
Explanation:
text[0:4]returns characters from index 0 to 3 (COMP).text[2:6]returns characters from index 2 to 5 (MPUT).text[-4:-1]uses negative indexing and returns PUT.
Q3. Differentiate between List and Tuple.
Answer :-
List and Tuple are two important collection data types in Python used to store multiple values. However, they differ in mutability, syntax, and usage.
| List | Tuple |
|---|---|
| A List is mutable, which means its elements can be changed. | A Tuple is immutable, which means its elements cannot be changed. |
| Lists are created using square brackets [ ]. | Tuples are created using parentheses ( ). |
| Items can be added, removed, or modified. | Items cannot be added, removed, or modified after creation. |
| Lists require more memory. | Tuples require less memory. |
| Lists are generally slower than tuples. | Tuples are generally faster than lists. |
Example of List:
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)
Output:
[10, 50, 30]
Example of Tuple:
numbers = (10, 20, 30)
print(numbers)
Output:
(10, 20, 30)
Q4. What is a Dictionary in Python?
Answer :-
A Dictionary is a built-in data type in Python that stores data in the form of key-value pairs. Each key in a dictionary is unique and is used to access its corresponding value. Dictionaries are mutable, which means their elements can be added, modified, or removed after creation.
Syntax:
dictionary_name = {
"key1": value1,
"key2": value2
}
Example:
# Creating a Dictionary
student = {
"Name": "Amit",
"Age": 18,
"Marks": 85
}
print(student)
Output:
{'Name': 'Amit', 'Age': 18, 'Marks': 85}
Explanation:
- The dictionary contains three key-value pairs.
- Name, Age, and Marks are the keys.
- Amit, 18, and 85 are the corresponding values.
- Values can be accessed using their keys.
Q5. What is the purpose of len() function?
Answer :-
The len() function in Python is used to determine the
length of an object. It returns the total number of
characters in a string or the total number of elements in a collection
such as a list, tuple, dictionary, or set.
Syntax:
len(object)
Example:
# Finding the length of a string
text = "Computer"
print(len(text))
Output:
8
Explanation:
- The string
"Computer"contains 8 characters. - The
len()function counts all the characters in the string and returns 8. - It can also be used to count the number of elements in lists, tuples, dictionaries, and other collections.
Q6. What is a User Defined Function?
Answer :-
A User Defined Function (UDF) is a function created by
the programmer to perform a specific task. It is defined using the
def keyword. User-defined functions help make programs
modular, reusable, and easier to understand.
Syntax:
def function_name():
# Function body
statements
Example:
# User Defined Function Example
def greet():
print("Welcome to Python!")
greet()
Output:
Welcome to Python!
Explanation:
- The
defkeyword is used to define a user-defined function. greet()is the name of the function.- The function prints the message "Welcome to Python!".
- The function is executed when it is called using
greet().
Q7. What is recursion?
Answer :-
Recursion is a programming technique in which a function calls itself to solve a problem. A recursive function repeatedly executes itself until a specified stopping condition, called the base case, is reached.
Syntax:
def function_name():
if condition:
return value
else:
return function_name()
Example:
# Recursive function to print numbers from 5 to 1
def display(n):
if n == 0:
return
print(n)
display(n - 1)
display(5)
Output:
5
4
3
2
1
Explanation:
- The function
display()calls itself repeatedly. - The value of
ndecreases by 1 in each recursive call. - When
nbecomes0, the base case is reached and the recursion stops. - Without a base case, the function would call itself indefinitely, causing a RecursionError.
Q8. What is the difference between append() and extend()?
Answer :-
Both append() and extend() are list methods in
Python used to add elements to a list. However, they work in different ways.
| append() | extend() |
|---|---|
| Adds a single element to the end of the list. | Adds multiple elements from another iterable to the end of the list. |
| The entire object is added as one element. | Each element of the iterable is added separately. |
| Increases the list size by one. | Increases the list size by the number of elements added. |
Example of append():
numbers = [10, 20, 30]
numbers.append([40, 50])
print(numbers)
Output:
[10, 20, 30, [40, 50]]
Example of extend():
numbers = [10, 20, 30]
numbers.extend([40, 50])
print(numbers)
Output:
[10, 20, 30, 40, 50]
Explanation:
append()adds the entire list[40, 50]as a single element.extend()adds each element (40and50) individually to the existing list.
Q9. What is the use of split() method?
Answer :-
The split() method in Python is used to divide a string into
a list of substrings. By default, it splits the string
wherever a space is found. A different separator can also be specified.
Syntax:
string_name.split(separator)
Note: The separator is optional. If no separator
is provided, the string is split using whitespace.
Example:
# Using split() method
text = "Python is easy to learn"
words = text.split()
print(words)
Output:
['Python', 'is', 'easy', 'to', 'learn']
Explanation:
- The string is divided into individual words.
- Each word becomes an element of a list.
- The
split()method is commonly used for processing text and user input.
Q10. What is the use of join() method?
Answer :-
The join() method in Python is used to
combine multiple strings into a single string. It joins
the elements of a list, tuple, or any iterable by placing a specified
separator between them.
Syntax:
separator.join(iterable)
Note: The separator can be a space, comma, hyphen, or any other string.
Example:
# Using join() method
words = ["Python", "is", "easy"]
result = " ".join(words)
print(result)
Output:
Python is easy
Explanation:
- The list
["Python", "is", "easy"]contains three strings. - The separator
" "(space) is inserted between each element. - The
join()method combines all the strings into one string. - The
join()method is commonly used to create formatted text from lists or tuples.
3 Marks
Q1. Explain List with suitable example.
Answer :-
A List is one of the most commonly used built-in data types in Python. It is an ordered and mutable collection of elements. A list can store multiple values of the same or different data types, such as integers, strings, floats, and Boolean values. Lists are created using square brackets [ ], and each element is separated by a comma.
Since lists are mutable, we can easily add, remove, or modify elements after
the list has been created. Lists also support indexing, slicing, and various
built-in methods such as append(), extend(),
insert(), remove(), and pop().
Syntax:
list_name = [element1, element2, element3, ...]
Example Program:
# Creating a List
students = ["Amit", "Riya", "Karan"]
print("Original List:")
print(students)
# Adding a new element
students.append("Neha")
print("Updated List:")
print(students)
Output:
Original List:
['Amit', 'Riya', 'Karan']
Updated List:
['Amit', 'Riya', 'Karan', 'Neha']
Explanation:
- The list
studentscontains the names of three students. - The
append()method adds "Neha" to the end of the list. - The updated list contains four elements.
- Elements in a list can be accessed using their index values starting from
0.
Features of List:
- Stores multiple values in a single variable.
- Maintains the order of elements.
- Allows duplicate values.
- Supports different data types in the same list.
- Elements can be modified, added, or removed.
Conclusion:
A List is a flexible and powerful data structure in Python used to store and manage collections of data. It is widely used because of its ability to hold multiple values and its support for various operations such as insertion, deletion, updating, and searching.
Q2. Explain Tuple and its characteristics.
Answer :-
A Tuple is a built-in data type in Python used to store multiple values in a single variable. It is an ordered and immutable collection, which means that once a tuple is created, its elements cannot be changed, added, or removed. Tuples are created using parentheses ( ), and the elements are separated by commas.
Tuples can store different types of data such as integers, strings, floating-point numbers, and Boolean values. They are commonly used when the data should remain constant throughout the program.
Syntax:
tuple_name = (element1, element2, element3, ...)
Example Program:
# Creating a Tuple
student = ("Amit", 18, 85.5)
print("Tuple:")
print(student)
# Accessing elements
print("Name:", student[0])
print("Age:", student[1])
print("Marks:", student[2])
Output:
Tuple:
('Amit', 18, 85.5)
Name: Amit
Age: 18
Marks: 85.5
Characteristics of Tuple:
- Immutable: Once created, the elements of a tuple cannot be modified.
- Ordered: Elements are stored in a fixed order and can be accessed using index values.
- Allows Duplicate Values: A tuple can contain duplicate elements.
- Supports Multiple Data Types: A tuple can store integers, strings, floats, Boolean values, etc.
- Indexed: The first element has index
0, and negative indexing is also supported. - Memory Efficient: Tuples consume less memory and are generally faster than lists.
Explanation:
- The tuple
studentstores a name, age, and marks. - The elements are accessed using index values such as
student[0]andstudent[1]. - Since tuples are immutable, attempting to modify an element will result in an error.
Conclusion:
A Tuple is a reliable data structure used to store a fixed collection of values. Because it is immutable, it provides better data security and performance than lists when the stored data does not need to be modified.
Q3. Explain Dictionary with example.
Answer :-
A Dictionary is a built-in data type in Python that stores data in the form of key-value pairs. Each key is unique and is used to access its corresponding value. Dictionaries are mutable, which means elements can be added, modified, or removed after creation.
Dictionaries are enclosed in curly braces { }, and each
key is separated from its value using a colon (:). Multiple
key-value pairs are separated by commas.
Syntax:
dictionary_name = {
"key1": value1,
"key2": value2,
"key3": value3
}
Example Program:
import pandas as pd
# Creating a Dictionary
student = {
"Name": "Amit",
"Age": 18,
"Marks": 85
}
# Displaying the Dictionary
print("Dictionary:")
print(student)
# Accessing values using keys
print("Name :", student["Name"])
print("Age :", student["Age"])
print("Marks :", student["Marks"])
Output:
Dictionary:
{'Name': 'Amit', 'Age': 18, 'Marks': 85}
Name : Amit
Age : 18
Marks : 85
Characteristics of Dictionary:
- Stores data in key-value pairs.
- Keys must be unique. Duplicate keys are not allowed.
- Mutable: Elements can be added, updated, or removed.
- Allows different data types such as integers, strings, floats, and Boolean values.
- Indexed by keys instead of numeric indexes.
- Enclosed in curly braces { }.
Explanation:
- The dictionary
studentcontains three key-value pairs. - Name, Age, and Marks are the keys.
- Amit, 18, and 85 are the corresponding values.
- The values are accessed using their keys, such as
student["Name"].
Conclusion:
A Dictionary is an efficient and flexible data structure used to store and manage data in the form of key-value pairs. It is widely used in Python applications because it provides fast data access, supports multiple data types, and allows easy updating of values.
Q4. Explain any three String Functions.
Answer :-
Python provides many built-in string functions (methods) to perform different operations on strings such as changing the case, splitting text, removing spaces, and searching for characters. These functions make string manipulation simple and efficient.
The following are three commonly used string functions:
1. upper() Function
The upper() function converts all the characters of a string
into uppercase letters.
Syntax:
string_name.upper()
Example:
text = "Python Programming"
print(text.upper())
Output:
PYTHON PROGRAMMING
2. lower() Function
The lower() function converts all the characters of a string
into lowercase letters.
Syntax:
string_name.lower()
Example:
text = "Python Programming"
print(text.lower())
Output:
python programming
3. split() Function
The split() function divides a string into a list of
substrings. By default, it splits the string wherever a space occurs.
Syntax:
string_name.split(separator)
Example:
text = "Python is easy to learn"
print(text.split())
Output:
['Python', 'is', 'easy', 'to', 'learn']
Summary Table
| Function | Purpose |
|---|---|
upper() |
Converts all characters of a string into uppercase letters. |
lower() |
Converts all characters of a string into lowercase letters. |
split() |
Splits a string into a list of substrings. |
Conclusion:
String functions are very useful for processing and manipulating text in
Python. Functions such as upper(), lower(), and
split() are commonly used in programs to format text, process
user input, and perform various string operations efficiently.
Q5. Explain append(), insert() and remove() methods.
Answer :-
Python provides several built-in methods to perform operations on lists.
The append(), insert(), and
remove() methods are commonly used to add and remove
elements from a list. These methods make list manipulation easy and
efficient.
1. append() Method
The append() method is used to add a single element to the
end of a list.
Syntax:
list_name.append(element)
Example:
fruits = ["Apple", "Banana"]
fruits.append("Mango")
print(fruits)
Output:
['Apple', 'Banana', 'Mango']
2. insert() Method
The insert() method is used to add an element at a
specified position in a list.
Syntax:
list_name.insert(index, element)
Example:
fruits = ["Apple", "Banana"]
fruits.insert(1, "Orange")
print(fruits)
Output:
['Apple', 'Orange', 'Banana']
3. remove() Method
The remove() method is used to remove the
first occurrence of a specified element from a list.
Syntax:
list_name.remove(element)
Example:
fruits = ["Apple", "Banana", "Mango"]
fruits.remove("Banana")
print(fruits)
Output:
['Apple', 'Mango']
Summary Table
| Method | Purpose |
|---|---|
append() |
Adds a single element to the end of the list. |
insert() |
Inserts an element at a specified index. |
remove() |
Removes the first occurrence of a specified element. |
Conclusion:
The append(), insert(), and
remove() methods are essential list operations in Python.
They allow programmers to add elements at the end, insert elements at
specific positions, and remove unwanted elements, making lists flexible
and easy to manage.
Q6. Differentiate between List and Dictionary.
Answer :-
List and Dictionary are two important built-in data structures in Python used to store collections of data. A List stores elements in an ordered sequence and uses numeric indexes to access them, whereas a Dictionary stores data as key-value pairs and uses unique keys to access values.
Difference between List and Dictionary
| List | Dictionary |
|---|---|
| Stores elements in an ordered sequence. | Stores data as key-value pairs. |
| Created using square brackets [ ]. | Created using curly braces { }. |
| Elements are accessed using numeric indexes. | Values are accessed using unique keys. |
| Allows duplicate elements. | Keys must be unique, but values can be duplicated. |
| Mutable (elements can be added, removed, or modified). | Mutable (key-value pairs can be added, updated, or removed). |
| Suitable for storing ordered collections of data. | Suitable for storing related data with meaningful keys. |
Example of List
# Creating a List
fruits = ["Apple", "Banana", "Mango"]
print(fruits)
Output
['Apple', 'Banana', 'Mango']
Example of Dictionary
# Creating a Dictionary
student = {
"Name": "Amit",
"Age": 18,
"Marks": 85
}
print(student)
Output
{'Name': 'Amit', 'Age': 18, 'Marks': 85}
Explanation:
- In a List, elements are accessed using index values such as
fruits[0]. - In a Dictionary, values are accessed using keys such as
student["Name"]. - Lists are useful for ordered collections, whereas dictionaries are useful for storing data with meaningful labels.
Conclusion:
Both List and Dictionary are powerful data structures in Python. Lists are ideal for storing ordered collections of data, while dictionaries are best suited for storing information in the form of key-value pairs for quick and efficient data retrieval.
Q7. Explain the use of Function in Python.
Answer :-
A function in Python is a block of reusable code that performs a specific task. Instead of writing the same code repeatedly, we can place it inside a function and call it whenever required. Functions improve the readability, organization, and reusability of a program.
Python provides two types of functions:
- Built-in Functions – Functions already available in Python, such as
print(),len(),input(), andtype(). - User Defined Functions – Functions created by the programmer using the
defkeyword.
Syntax:
def function_name(parameters):
# Function body
statements
return value
Example Program:
# User Defined Function
def add(a, b):
sum = a + b
return sum
result = add(10, 20)
print("Sum =", result)
Output:
Sum = 30
Uses (Advantages) of Functions:
- Code Reusability: A function can be called multiple times without rewriting the code.
- Reduces Code Duplication: Repeated code is written only once inside the function.
- Improves Readability: Programs become easier to understand and maintain.
- Easy Debugging: Errors can be identified and corrected easily because the program is divided into smaller parts.
- Modular Programming: Large programs can be divided into smaller, manageable modules.
Explanation:
- The
add()function accepts two numbers as parameters. - It calculates their sum and returns the result using the
returnstatement. - The returned value is stored in the variable
result. - The
print()function displays the final output.
Conclusion:
Functions are one of the most important features of Python. They make programs shorter, more organized, and easier to maintain. By using functions, programmers can write efficient, reusable, and modular code.
Q8. Explain Formal and Actual Parameters.
Answer :-
In Python, parameters are variables used to pass data between a function and the function call. There are two types of parameters: Formal Parameters and Actual Parameters (Arguments).
1. Formal Parameters
Formal Parameters are the variables declared in the function definition. They receive values from the function call and are used only inside the function.
Example:
def add(a, b):
return a + b
In the above example, a and b are
formal parameters.
2. Actual Parameters (Arguments)
Actual Parameters, also called arguments, are the values passed to the function when it is called. These values are assigned to the formal parameters.
Example:
result = add(10, 20)
Here, 10 and 20 are
actual parameters (arguments).
Complete Program:
# Function with Formal and Actual Parameters
def add(a, b):
sum = a + b
return sum
result = add(10, 20)
print("Sum =", result)
Output:
Sum = 30
Difference between Formal and Actual Parameters
| Formal Parameters | Actual Parameters |
|---|---|
| Declared in the function definition. | Passed during the function call. |
| Act as placeholders for receiving values. | Provide the actual values to the function. |
| Used only inside the function. | Can be constants, variables, or expressions. |
Example: a, b |
Example: 10, 20 |
Explanation:
- The function
add(a, b)defines two formal parameters:aandb. - When the function is called as
add(10, 20), the values10and20become the actual parameters. - The actual parameters are assigned to the formal parameters, and the function computes their sum.
Conclusion:
Formal and actual parameters are essential for passing data to functions. Formal parameters receive values inside the function, whereas actual parameters supply those values during the function call. Together, they make functions flexible, reusable, and easy to use.
Q9. Write a short note on Recursion.
Answer :-
Recursion is a programming technique in which a function calls itself repeatedly to solve a problem. A recursive function breaks a large problem into smaller sub-problems of the same type. The recursive calls continue until a special condition, known as the base case, is reached. The base case stops further recursive calls and prevents the function from running indefinitely.
Recursion is commonly used to solve problems such as calculating the factorial of a number, generating the Fibonacci series, searching in tree structures, and solving mathematical problems.
Syntax:
def function_name(parameters):
if base_condition:
return value
else:
return function_name(modified_parameters)
Example Program:
# Recursive function to calculate factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print("Factorial =", result)
Output:
Factorial = 120
Explanation:
- The function
factorial()calls itself with a smaller value ofn. - The recursive calls continue until
n == 1, which is the base case. - Once the base case is reached, the function returns values back through each previous call.
- The final result of
5 × 4 × 3 × 2 × 1is 120.
Advantages of Recursion:
- Reduces the complexity of solving repetitive problems.
- Makes the program shorter and easier to understand.
- Useful for solving problems that can be divided into smaller sub-problems.
- Widely used in tree traversal, searching, and mathematical computations.
Disadvantages of Recursion:
- Consumes more memory because each function call is stored in the call stack.
- May be slower than iteration due to repeated function calls.
- If a base case is not provided, it can result in a RecursionError.
Conclusion:
Recursion is a powerful programming technique that allows a function to call itself to solve complex problems in a simple and elegant way. However, every recursive function must include a base case to terminate the recursion and avoid infinite execution.
Q10. Explain the Random Module.
Answer :-
The Random Module is a built-in Python module that is used to generate random numbers and perform random operations. It is commonly used in games, simulations, password generation, lotteries, quizzes, and other applications where random values are required.
Before using the random module, it must be imported into the program
using the import random statement.
Syntax:
import random
Commonly Used Functions of the Random Module:
| Function | Purpose |
|---|---|
random.randint(a, b) |
Returns a random integer between a and b (inclusive). |
random.random() |
Returns a random floating-point number between 0.0 and 1.0. |
random.choice(sequence) |
Returns a random element from a list, tuple, or string. |
random.shuffle(list) |
Randomly rearranges the elements of a list. |
Example Program:
import random
# Generate a random integer between 1 and 100
number = random.randint(1, 100)
print("Random Number:", number)
Sample Output:
Random Number: 57
Note: The output may be different each time the program is executed because the number is generated randomly.
Explanation:
- The
import randomstatement imports the Random module. - The
random.randint(1, 100)function generates a random integer between 1 and 100. - The generated number is stored in the variable
number. - The
print()function displays the random number on the screen.
Applications of the Random Module:
- Developing games such as dice, cards, and lottery applications.
- Generating random passwords and OTPs.
- Creating quiz and exam applications.
- Performing simulations and probability-based experiments.
- Selecting random items from a collection.
Conclusion:
The Random Module is an important Python module that provides functions to generate random numbers and perform random operations. It is widely used in game development, simulations, security applications, and many real-world Python programs.
Q11. Explain Exception Handling.
Answer :-
Exception Handling is a mechanism in Python used to handle runtime errors (exceptions) without terminating the program abruptly. It allows the program to continue executing even if an error occurs, making the program more reliable and user-friendly.
Python provides the try, except,
else, and finally blocks for handling
exceptions.
Syntax:
try:
# Code that may generate an exception
except ExceptionType:
# Code to handle the exception
else:
# Executes if no exception occurs
finally:
# Executes whether an exception occurs or not
Example Program:
# Exception Handling Example
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result =", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid numeric values.")
finally:
print("Program Executed Successfully.")
Sample Output 1:
Enter first number: 20
Enter second number: 5
Result = 4.0
Program Executed Successfully.
Sample Output 2:
Enter first number: 20
Enter second number: 0
Error: Division by zero is not allowed.
Program Executed Successfully.
Explanation:
- The
tryblock contains the code that may produce an exception. - The
exceptblock handles specific exceptions such asZeroDivisionErrorandValueError. - The
finallyblock is always executed, whether an exception occurs or not. - Exception handling prevents the program from terminating unexpectedly.
Advantages of Exception Handling:
- Prevents abrupt termination of the program.
- Improves program reliability and robustness.
- Allows developers to display meaningful error messages.
- Makes debugging and maintenance easier.
- Ensures important cleanup code executes using the
finallyblock.
Conclusion:
Exception Handling is an essential feature of Python that helps manage
runtime errors effectively. By using the
try, except, else, and
finally blocks, programmers can create robust, secure, and
user-friendly applications.
Q12. Explain any three Dictionary Methods.
Answer :-
Python provides several built-in methods to perform operations on
dictionaries. These methods help in accessing, updating, and removing
data stored in the form of key-value pairs. Some commonly used dictionary
methods are keys(), values(), and
items().
1. keys() Method
The keys() method returns a view object containing all the
keys present in a dictionary.
Syntax:
dictionary_name.keys()
Example:
student = {
"Name": "Amit",
"Age": 18,
"Marks": 85
}
print(student.keys())
Output:
dict_keys(['Name', 'Age', 'Marks'])
2. values() Method
The values() method returns a view object containing all the
values stored in the dictionary.
Syntax:
dictionary_name.values()
Example:
student = {
"Name": "Amit",
"Age": 18,
"Marks": 85
}
print(student.values())
Output:
dict_values(['Amit', 18, 85])
3. items() Method
The items() method returns all key-value pairs as tuples in
a view object.
Syntax:
dictionary_name.items()
Example:
student = {
"Name": "Amit",
"Age": 18,
"Marks": 85
}
print(student.items())
Output:
dict_items([('Name', 'Amit'), ('Age', 18), ('Marks', 85)])
Summary Table
| Method | Purpose |
|---|---|
keys() |
Returns all keys of the dictionary. |
values() |
Returns all values of the dictionary. |
items() |
Returns all key-value pairs as tuples. |
Advantages of Dictionary Methods:
- Provide an easy way to access dictionary data.
- Help retrieve keys, values, and key-value pairs efficiently.
- Make dictionary operations simple and readable.
- Useful while iterating through dictionaries.
Conclusion:
Dictionary methods such as keys(),
values(), and items() are essential for
accessing and managing data stored in dictionaries. These methods make
Python programs more efficient, readable, and easier to maintain.
Q14. Explain Mutable and Immutable Data Types.
Answer :-
In Python, data types are classified into Mutable and Immutable based on whether their values can be changed after they are created.
Mutable data types allow modification of their contents without creating a new object, whereas Immutable data types cannot be modified once they are created. If changes are required in an immutable object, Python creates a new object instead of modifying the existing one.
1. Mutable Data Types
Mutable means the value of an object can be changed after it is created. Elements can be added, removed, or modified without creating a new object.
Examples:
- List
- Dictionary
- Set
Example Program:
# Mutable Data Type (List)
numbers = [10, 20, 30]
numbers[1] = 50
print(numbers)
Output:
[10, 50, 30]
In the above example, the second element of the list is modified from 20 to 50.
2. Immutable Data Types
Immutable means the value of an object cannot be changed after it is created. Any modification results in the creation of a new object.
Examples:
- String
- Tuple
- Integer
- Float
- Boolean
Example Program:
# Immutable Data Type (String)
text = "Python"
# Creating a new string
text = text + " Programming"
print(text)
Output:
Python Programming
In this example, the original string is not modified. Instead, Python creates a new string object containing the updated value.
Difference between Mutable and Immutable Data Types
| Mutable Data Types | Immutable Data Types |
|---|---|
| Can be modified after creation. | Cannot be modified after creation. |
| Changes are made in the same object. | Changes create a new object. |
| Examples: List, Dictionary, Set. | Examples: String, Tuple, Integer, Float, Boolean. |
| Suitable for frequently changing data. | Suitable for fixed or constant data. |
Advantages:
- Mutable Data Types: Easy to update and modify data efficiently.
- Immutable Data Types: Provide better security and help prevent accidental changes to data.
Conclusion:
Understanding mutable and immutable data types is important in Python programming. Mutable objects are useful when data needs to change frequently, whereas immutable objects are ideal for storing fixed data, improving program reliability and performance.
Q15. Explain the difference between count() and index().
Answer :-
The count() and index() methods are commonly
used with strings and lists in Python. Although both methods are used to
search for data, they perform different tasks.
- count() is used to count how many times a specified element or substring occurs.
- index() is used to find the position (index) of the first occurrence of a specified element or substring.
1. count() Method
The count() method returns the total number of times a
specified value appears in a string or list.
Syntax:
string_name.count(value)
list_name.count(value)
Example:
text = "banana"
print(text.count("a"))
Output:
3
2. index() Method
The index() method returns the index (position) of the
first occurrence of a specified value. If the value is not found, it
raises a ValueError.
Syntax:
string_name.index(value)
list_name.index(value)
Example:
text = "banana"
print(text.index("a"))
Output:
1
Difference between count() and index()
count() |
index() |
|---|---|
| Returns the number of occurrences of a value. | Returns the position (index) of the first occurrence of a value. |
| Returns an integer representing the frequency. | Returns an integer representing the index position. |
| If the value is not found, it returns 0. | If the value is not found, it raises a ValueError. |
| Used when the number of occurrences is required. | Used when the location of an element is required. |
Explanation:
- In the string
"banana", the character'a'appears 3 times, socount("a")returns 3. - The first occurrence of
'a'is at index 1, soindex("a")returns 1. - Use
count()to determine frequency andindex()to determine position.
Conclusion:
Both count() and index() are useful search
methods in Python. The count() method counts the number of
occurrences of a value, whereas the index() method finds
the position of the first occurrence. Choosing the appropriate method
depends on the requirement of the program.


