Unit 3
2 marks Important Question of Python Programming
Q1 What is the difference between list
and tuples in Python? [ 2019-20]
Solution:
In Python,
both lists and tuples are used to store a collection of values. However, there
are some key differences between them:
- Mutability:
Lists are mutable, which means you can add, remove, or change elements in a
list after it is created. Tuples are immutable, which means you cannot change
the elements of a tuple once it is created.
- Syntax: Lists
are created using square brackets [], while tuples are created using
parentheses ().
- Usage: Lists
are typically used for collections of homogeneous elements (i.e., elements of
the same type), and when you need to modify the collection frequently. Tuples
are often used for collections of heterogeneous elements (i.e., elements of
different types), and when you need to ensure that the collection is immutable
and can’t be changed accidentally.
- Performance:
Tuples are generally faster than lists for accessing elements because they are
implemented as a contiguous block of memory, whereas lists use a dynamic array
that may need to be resized as elements are added or removed.
Here are some
examples of creating and using lists and tuples:
# Create a
list
my_list = [1,
2, 3, 4]
# Modify a
list
my_list[0] =
5
# Add an
element to a list
my_list.append(6)
# Create a
tuple
my_tuple =
(1, “two”, 3.0)
# Access an
element in a tuple
print(my_tuple[1])
Q2 What is the difference between
Python Arrays and lists? [
2019-20]
Solution:
In Python, arrays and lists are both used to store collections of values. However, there are some key differences between them:
Homogeneity: Arrays are homogeneous, which means that all elements must be of the same data type. Lists, on the other hand, can contain elements of different data types.
Memory usage: Arrays are generally more memory-efficient than lists for storing large amounts of data because they store data in contiguous memory locations. Lists, on the other hand, use a dynamic array implementation, which can result in memory fragmentation and higher memory usage.
Performance: Arrays can be faster than lists for certain operations, such as element access and slicing, because they are implemented in lower-level languages like C, and their memory layout is more predictable.
Flexibility: Lists are more flexible than arrays because they can grow and shrink dynamically, while arrays have a fixed size that must be specified at the time of creation.
Here are some examples of creating and using arrays and lists:
# Import the array module
import array
# Create an array of integers
my_array = array.array(‘i’, [1, 2, 3, 4])
# Access an element in the array
print(my_array[1])
# Create a list
my_list = [1, 2, ‘three’, 4.0]
# Access an element in the list
print(my_list[2])
# Add an element to the list
my_list.append(5)
# Create a sublist
my_sublist = my_list[1:3]
Q3 Differentiate Fruitful functions and void functions. [ 2019-20]
Solution:
In Python, functions can be classified into two types: fruitful functions and void functions.
1. Fruitful Functions:
Fruitful functions are functions that return a value after executing. They are also called “value-returning” functions. Fruitful functions are used when you want to perform some computation and return the result. You can assign the result of a fruitful function to a variable, or use it as an input to another function or expression.
Here is an example of a fruitful function that takes two numbers as input and returns their sum:
def add_numbers(a, b):
sum = a + b
return sum
result = add_numbers(3, 4)
print(result) # Output: 7
2. Void Functions:
Void functions are functions that do not return a value after executing. They are also called “non-value-returning” functions. Void functions are used when you want to perform some action, such as printing output to the console, but you do not need to return a result.
Here is an example of a void function that takes a list as input and prints each element in the list:
def print_list(my_list):
for element in my_list:
print(element)
my_list = [1, 2, 3, 4]
print_list(my_list) # Output: 1, 2, 3, 4
In summary, the main difference between fruitful and void functions is that fruitful functions return a value after executing, while void functions do not return a value.
Q4 Write a recursive python function “rprint” to print all elements in a list reverse.
Rprint([]) prints nothing
Rprint([1,2,3]) prints 3,2,1 [2020-2021]
Solution:
Here is a recursive Python function “rprint” that prints all elements in a list in reverse:
def rprint(my_list):
if len(my_list) == 0:
return
else:
rprint(my_list[1:])
print(my_list[0], end=” “)
# Test the function
rprint([]) # Output: (nothing)
rprint([1, 2, 3]) # Output: 3 2 1
Explanation:
The function takes a list as input and checks if the list is empty. If the list is empty, it returns without doing anything. Otherwise, it calls itself recursively with the rest of the list (i.e., all elements except the first element) and then prints the first element. This continues until the entire list has been printed in reverse.
In the base case, when the list is empty, the function simply returns without doing anything. In the recursive case, the function calls itself with a smaller input, and then performs some operation on the input (i.e., printing the first element).
Note that the end=” ” parameter in the print statement is used to print a space after each element, rather than a newline character. This ensures that all elements are printed on the same line, separated by spaces.
Q5 Consider the program :
X = [’12 ’, ‘hello’, 456]
X[0] *= 3
X[1][1] = ‘bye’
Explain why this program generates an error.
[2020-2021]
Solution:
The program generates an error because of the following reasons:
- X[0] *= 3 – This statement tries to multiply the string ’12 ‘ by 3, which results in a new string ‘121212 ‘. However, the original list X contains strings and an integer. Multiplying a string by an integer is a valid operation in Python, but it creates a new string and replaces the original value in the list. In this case, the new string ‘121212 ‘ is not compatible with the original integer and string in the list.
- X[1][1] = ‘bye’ – This statement tries to modify the second character of the string ‘hello’ to ‘b’. However, strings in Python are immutable, which means that you cannot modify them directly. Instead, you need to create a new string with the modified characters. In this case, the attempt to modify the string ‘hello’ in-place generates an error.
To avoid these errors, you can use appropriate data types and operations that are compatible with the elements in the list. For example, you can use integer multiplication for integers and string concatenation for strings. You can also create a new string with the modified characters instead of modifying the original string. Here is a corrected version of the program:
X = [’12’, ‘hello’, 456]
X[0] = X[0] * 3
X[1] = X[1][:1] + ‘bye’ + X[1][2:]
print(X) # Output: [‘121212’, ‘hbyeo’, 456]
In this version, the integer and string elements in the list are not mixed, and the string modification is done by creating a new string with the modified characters.
Q6 What is the output of the following program ?
(lambda x,y : y – 2*x) (1,11) [2020-2021]
Solution:
The output of the following program will be:
9
Explanation:
The program defines an anonymous function using lambda, which takes two arguments x and y and returns the result of y – 2*x. Then, the function is called with the arguments (1, 11).
Substituting x=1 and y=11 into the lambda function, we get:
y – 2*x = 11 – 2*1 = 9
Therefore, the output of the program is 9.
Q7 What will be the output of following python code?
Def cube(X):
return X*X*X
x= cube(3)
print(x)
[2021-22]
Solution:
The output of the following Python code will be:27
Explanation:
The code defines a function cube(X) that takes a number as input and returns its cube. Then, it calls the function with the argument 3 and assigns the returned value 27 to the variable x. Finally, it prints the value of x, which is 27.
Therefore, the output of the program is 27.
Q8 Write a python program to remove multiple elements from a list in Python.
Solution:
Here is a Python program to remove multiple elements from a list based on their indices:
my_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]
indices_to_remove = [1, 3, 5]
# Sort the indices in descending order to avoid index shifting
indices_to_remove.sort(reverse=True)
# Remove the elements from the list based on their indices
for index in indices_to_remove:
del my_list[index]
# Print the updated list
print(my_list) # Output: [‘a’, ‘c’, ‘e’, ‘g’]
Explanation:
The program defines a list my_list and a list of indices indices_to_remove that correspond to the elements to be removed from the list. In this example, the elements with indices 1, 3, and 5 (i.e., ‘b’, ‘d’, and ‘f’) will be removed from the list.
To remove multiple elements from a list in Python, you can loop through the list of indices to be removed and use the del keyword to delete the corresponding elements from the list. Note that we sort the list of indices in descending order before removing the elements to avoid index shifting. This ensures that the correct elements are removed from the list.
Finally, we print the updated list after removing the specified elements.
Note that this approach modifies the original list in place. If you want to create a new list without the specified elements, you can use a list comprehension or the filter() function.
Here is an Another Python program to remove multiple elements from a list based on their values:
my_list = [‘apple’, ‘banana’, ‘orange’, ‘grape’, ‘kiwi’, ‘pear’]
elements_to_remove = [‘banana’, ‘grape’, ‘pear’]
# Use list comprehension to create a new list without the specified elements
new_list = [element for element in my_list if element not in elements_to_remove]
# Print the updated list
print(new_list) # Output: [‘apple’, ‘orange’, ‘kiwi’]
Explanation:
The program defines a list my_list and a list of elements elements_to_remove that correspond to the elements to be removed from the list. In this example, the elements ‘banana’, ‘grape’, and ‘pear’ will be removed from the list.
To remove multiple elements from a list in Python based on their values, you can use a list comprehension to create a new list that excludes the specified elements. In this case, we iterate over each element in my_list and only include it in the new list if it is not in elements_to_remove.
Finally, we print the updated list without the specified elements.
Note that this approach creates a new list and does not modify the original list in place. If you want to modify the original list in place, you can use a loop and the remove() method.
Q9 What is slicing ? What is the use of docstring ?
Solution:
1. Slicing:
Slicing in Python is a way to extract a part of a sequence (e.g., a list, tuple, or string) by specifying a range of indices. The syntax for slicing is seq[start:end:step], where start is the index of the first element to include, end is the index of the first element to exclude, and step is the increment between elements to include. If start is omitted, it defaults to 0; if end is omitted, it defaults to the length of the sequence; if step is omitted, it defaults to 1.
Here is an example of slicing a list:
my_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
sliced_list = my_list[1:4] # [‘b’, ‘c’, ‘d’]
In this example, sliced_list contains the elements of my_list with indices 1, 2, and 3 (i.e., ‘b’, ‘c’, and ‘d’), which are specified using slicing.
2.Docstring:
A docstring in Python is a string literal that appears as the first statement in a module, function, class, or method definition. It is used to document the purpose, arguments, return value, and other details of the code. Docstrings are enclosed in triple quotes (“””) and can span multiple lines.
Here is an example of a function with a docstring:
def square(x):
“””Return the square of a number.”””
return x**2
In this example, the docstring “””Return the square of a number.””” documents the purpose of the function square().
Docstrings can be accessed using the __doc__ attribute of the object, as shown in the following example:
print(square.__doc__) # Output: “Return the square of a number.”
Docstrings are a useful way to provide documentation for your code and make it more readable and maintainable.
Q10 What is the output of print list[2] when list = [‘abcd’, 2.23, ‘john’] ?
Solution:
The output of print list[2] when list = [‘abcd’, 2.23, ‘john’] will be ‘john’.
This is because list[2] accesses the element at index 2 of the list, which is ‘john’. In Python, list indices start at 0, so list[0] would access the first element of the list (‘abcd’), list[1] would access the second element (2.23), and list[2] would access the third element (‘john’).
Q11. Give one-one example for zip, max and min methods.
Solution:
here are some examples:
1. zip() method:
The zip() method is used to aggregate elements from two or more iterable objects (e.g., lists, tuples, or strings) into tuples based on their indices. It returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.
Example:
names = [‘Alice’, ‘Bob’, ‘Charlie’]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
Output:
Alice 25
Bob 30
Charlie 35
2. max() method:
The max() method is used to find the largest element in an iterable object (e.g., list, tuple, or set).
Example:
numbers = [1, 5, 3, 7, 2, 8]
max_num = max(numbers)
print(max_num)
Output:
8
3. min() method:
The min() method is used to find the smallest element in an iterable object (e.g., list, tuple, or set).
Example:
numbers = [1, 5, 3, 7, 2, 8]
min_num = min(numbers)
print(min_num)
Output:
1
You may Like to Read this
Q1 What is the difference between list
and tuples in Python? [ 2019-20]
and tuples in Python? [ 2019-20]
Solution:
In Python,
both lists and tuples are used to store a collection of values. However, there
are some key differences between them:
both lists and tuples are used to store a collection of values. However, there
are some key differences between them:
- Mutability:
Lists are mutable, which means you can add, remove, or change elements in a
list after it is created. Tuples are immutable, which means you cannot change
the elements of a tuple once it is created. - Syntax: Lists
are created using square brackets [], while tuples are created using
parentheses (). - Usage: Lists
are typically used for collections of homogeneous elements (i.e., elements of
the same type), and when you need to modify the collection frequently. Tuples
are often used for collections of heterogeneous elements (i.e., elements of
different types), and when you need to ensure that the collection is immutable
and can’t be changed accidentally. - Performance:
Tuples are generally faster than lists for accessing elements because they are
implemented as a contiguous block of memory, whereas lists use a dynamic array
that may need to be resized as elements are added or removed.
Here are some
examples of creating and using lists and tuples:
examples of creating and using lists and tuples:
# Create a
list
list
my_list = [1,
2, 3, 4]
2, 3, 4]
# Modify a
list
list
my_list[0] =
5
5
# Add an
element to a list
element to a list
my_list.append(6)
# Create a
tuple
tuple
my_tuple =
(1, “two”, 3.0)
(1, “two”, 3.0)
# Access an
element in a tuple
element in a tuple
print(my_tuple[1])
Q2 What is the difference between
Python Arrays and lists? [
2019-20]
Solution:
In Python, arrays and lists are both used to store collections of values. However, there are some key differences between them:
Homogeneity: Arrays are homogeneous, which means that all elements must be of the same data type. Lists, on the other hand, can contain elements of different data types.
Memory usage: Arrays are generally more memory-efficient than lists for storing large amounts of data because they store data in contiguous memory locations. Lists, on the other hand, use a dynamic array implementation, which can result in memory fragmentation and higher memory usage.
Performance: Arrays can be faster than lists for certain operations, such as element access and slicing, because they are implemented in lower-level languages like C, and their memory layout is more predictable.
Flexibility: Lists are more flexible than arrays because they can grow and shrink dynamically, while arrays have a fixed size that must be specified at the time of creation.
Here are some examples of creating and using arrays and lists:
# Import the array module
import array
# Create an array of integers
my_array = array.array(‘i’, [1, 2, 3, 4])
# Access an element in the array
print(my_array[1])
# Create a list
my_list = [1, 2, ‘three’, 4.0]
# Access an element in the list
print(my_list[2])
# Add an element to the list
my_list.append(5)
# Create a sublist
my_sublist = my_list[1:3]
Q3 Differentiate Fruitful functions and void functions. [ 2019-20]
Solution:
In Python, functions can be classified into two types: fruitful functions and void functions.
1. Fruitful Functions:
Fruitful functions are functions that return a value after executing. They are also called “value-returning” functions. Fruitful functions are used when you want to perform some computation and return the result. You can assign the result of a fruitful function to a variable, or use it as an input to another function or expression.
Here is an example of a fruitful function that takes two numbers as input and returns their sum:
def add_numbers(a, b):
sum = a + b
return sum
result = add_numbers(3, 4)
print(result) # Output: 7
2. Void Functions:
Void functions are functions that do not return a value after executing. They are also called “non-value-returning” functions. Void functions are used when you want to perform some action, such as printing output to the console, but you do not need to return a result.
Here is an example of a void function that takes a list as input and prints each element in the list:
def print_list(my_list):
for element in my_list:
print(element)
my_list = [1, 2, 3, 4]
print_list(my_list) # Output: 1, 2, 3, 4
In summary, the main difference between fruitful and void functions is that fruitful functions return a value after executing, while void functions do not return a value.
Q4 Write a recursive python function “rprint” to print all elements in a list reverse.
Rprint([]) prints nothing
Rprint([1,2,3]) prints 3,2,1 [2020-2021]
Solution:
Here is a recursive Python function “rprint” that prints all elements in a list in reverse:
def rprint(my_list):
if len(my_list) == 0:
return
else:
rprint(my_list[1:])
print(my_list[0], end=” “)
# Test the function
rprint([]) # Output: (nothing)
rprint([1, 2, 3]) # Output: 3 2 1
Explanation:
The function takes a list as input and checks if the list is empty. If the list is empty, it returns without doing anything. Otherwise, it calls itself recursively with the rest of the list (i.e., all elements except the first element) and then prints the first element. This continues until the entire list has been printed in reverse.
In the base case, when the list is empty, the function simply returns without doing anything. In the recursive case, the function calls itself with a smaller input, and then performs some operation on the input (i.e., printing the first element).
Note that the end=” ” parameter in the print statement is used to print a space after each element, rather than a newline character. This ensures that all elements are printed on the same line, separated by spaces.
Q5 Consider the program :
X = [’12 ’, ‘hello’, 456]
X[0] *= 3
X[1][1] = ‘bye’
Explain why this program generates an error.
[2020-2021]
Solution:
The program generates an error because of the following reasons:
- X[0] *= 3 – This statement tries to multiply the string ’12 ‘ by 3, which results in a new string ‘121212 ‘. However, the original list X contains strings and an integer. Multiplying a string by an integer is a valid operation in Python, but it creates a new string and replaces the original value in the list. In this case, the new string ‘121212 ‘ is not compatible with the original integer and string in the list.
- X[1][1] = ‘bye’ – This statement tries to modify the second character of the string ‘hello’ to ‘b’. However, strings in Python are immutable, which means that you cannot modify them directly. Instead, you need to create a new string with the modified characters. In this case, the attempt to modify the string ‘hello’ in-place generates an error.
To avoid these errors, you can use appropriate data types and operations that are compatible with the elements in the list. For example, you can use integer multiplication for integers and string concatenation for strings. You can also create a new string with the modified characters instead of modifying the original string. Here is a corrected version of the program:
X = [’12’, ‘hello’, 456]
X[0] = X[0] * 3
X[1] = X[1][:1] + ‘bye’ + X[1][2:]
print(X) # Output: [‘121212’, ‘hbyeo’, 456]
In this version, the integer and string elements in the list are not mixed, and the string modification is done by creating a new string with the modified characters.
Q6 What is the output of the following program ?
(lambda x,y : y – 2*x) (1,11) [2020-2021]
Solution:
The output of the following program will be:
9
Explanation:
The program defines an anonymous function using lambda, which takes two arguments x and y and returns the result of y – 2*x. Then, the function is called with the arguments (1, 11).
Substituting x=1 and y=11 into the lambda function, we get:
y – 2*x = 11 – 2*1 = 9
Therefore, the output of the program is 9.
Q7 What will be the output of following python code?
Def cube(X):
return X*X*X
x= cube(3)
print(x)
[2021-22]
Solution:
The output of the following Python code will be:27
Explanation:
The code defines a function cube(X) that takes a number as input and returns its cube. Then, it calls the function with the argument 3 and assigns the returned value 27 to the variable x. Finally, it prints the value of x, which is 27.
Therefore, the output of the program is 27.
Q8 Write a python program to remove multiple elements from a list in Python.
Solution:
Here is a Python program to remove multiple elements from a list based on their indices:
my_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]
indices_to_remove = [1, 3, 5]
# Sort the indices in descending order to avoid index shifting
indices_to_remove.sort(reverse=True)
# Remove the elements from the list based on their indices
for index in indices_to_remove:
del my_list[index]
# Print the updated list
print(my_list) # Output: [‘a’, ‘c’, ‘e’, ‘g’]
Explanation:
The program defines a list my_list and a list of indices indices_to_remove that correspond to the elements to be removed from the list. In this example, the elements with indices 1, 3, and 5 (i.e., ‘b’, ‘d’, and ‘f’) will be removed from the list.
To remove multiple elements from a list in Python, you can loop through the list of indices to be removed and use the del keyword to delete the corresponding elements from the list. Note that we sort the list of indices in descending order before removing the elements to avoid index shifting. This ensures that the correct elements are removed from the list.
Finally, we print the updated list after removing the specified elements.
Note that this approach modifies the original list in place. If you want to create a new list without the specified elements, you can use a list comprehension or the filter() function.
Here is an Another Python program to remove multiple elements from a list based on their values:
my_list = [‘apple’, ‘banana’, ‘orange’, ‘grape’, ‘kiwi’, ‘pear’]
elements_to_remove = [‘banana’, ‘grape’, ‘pear’]
# Use list comprehension to create a new list without the specified elements
new_list = [element for element in my_list if element not in elements_to_remove]
# Print the updated list
print(new_list) # Output: [‘apple’, ‘orange’, ‘kiwi’]
Explanation:
The program defines a list my_list and a list of elements elements_to_remove that correspond to the elements to be removed from the list. In this example, the elements ‘banana’, ‘grape’, and ‘pear’ will be removed from the list.
To remove multiple elements from a list in Python based on their values, you can use a list comprehension to create a new list that excludes the specified elements. In this case, we iterate over each element in my_list and only include it in the new list if it is not in elements_to_remove.
Finally, we print the updated list without the specified elements.
Note that this approach creates a new list and does not modify the original list in place. If you want to modify the original list in place, you can use a loop and the remove() method.
Q9 What is slicing ? What is the use of docstring ?
Solution:
1. Slicing:
Slicing in Python is a way to extract a part of a sequence (e.g., a list, tuple, or string) by specifying a range of indices. The syntax for slicing is seq[start:end:step], where start is the index of the first element to include, end is the index of the first element to exclude, and step is the increment between elements to include. If start is omitted, it defaults to 0; if end is omitted, it defaults to the length of the sequence; if step is omitted, it defaults to 1.
Here is an example of slicing a list:
my_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
sliced_list = my_list[1:4] # [‘b’, ‘c’, ‘d’]
In this example, sliced_list contains the elements of my_list with indices 1, 2, and 3 (i.e., ‘b’, ‘c’, and ‘d’), which are specified using slicing.
2.Docstring:
A docstring in Python is a string literal that appears as the first statement in a module, function, class, or method definition. It is used to document the purpose, arguments, return value, and other details of the code. Docstrings are enclosed in triple quotes (“””) and can span multiple lines.
Here is an example of a function with a docstring:
def square(x):
“””Return the square of a number.”””
return x**2
In this example, the docstring “””Return the square of a number.””” documents the purpose of the function square().
Docstrings can be accessed using the __doc__ attribute of the object, as shown in the following example:
print(square.__doc__) # Output: “Return the square of a number.”
Docstrings are a useful way to provide documentation for your code and make it more readable and maintainable.
Q10 What is the output of print list[2] when list = [‘abcd’, 2.23, ‘john’] ?
Solution:
The output of print list[2] when list = [‘abcd’, 2.23, ‘john’] will be ‘john’.
This is because list[2] accesses the element at index 2 of the list, which is ‘john’. In Python, list indices start at 0, so list[0] would access the first element of the list (‘abcd’), list[1] would access the second element (2.23), and list[2] would access the third element (‘john’).
Q11. Give one-one example for zip, max and min methods.
Solution:
here are some examples:
1. zip() method:
The zip() method is used to aggregate elements from two or more iterable objects (e.g., lists, tuples, or strings) into tuples based on their indices. It returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.
Example:
names = [‘Alice’, ‘Bob’, ‘Charlie’]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
Output:
Alice 25
Bob 30
Charlie 35
2. max() method:
The max() method is used to find the largest element in an iterable object (e.g., list, tuple, or set).
Example:
numbers = [1, 5, 3, 7, 2, 8]
max_num = max(numbers)
print(max_num)
Output:
8
3. min() method:
The min() method is used to find the smallest element in an iterable object (e.g., list, tuple, or set).
Example:
numbers = [1, 5, 3, 7, 2, 8]
min_num = min(numbers)
print(min_num)
Output:
1
You may Like to Read this
PYTHON PROGRAMMING ALL STUDY MATERIAL || 99+ MOST IMPORTANT QUESTION WITH SOLUTION