Array Question Bank
Array Question Bank
When searching for the minimum in an unsorted list multiple times, you can sort
the list once to save time during subsequent operations. However, sorting upfront
takes additional time.
Trade-off: Sorting saves time during repeated queries but incurs an upfront cost.
When searching for items, dictionaries offer faster lookups but consume more
memory compared to lists.
data = {10: True, 20: True, 30: True, 40: True, 50: True}
Trade-off:
● The list is simpler and uses less memory but has slower lookups.
● The dictionary speeds up lookups at the cost of increased memory usage.
2. Explain the way of Finding the Maximum number in an array and minimum
number from an ordered array with suitable example programs.
Answer) To find the maximum number in an array, we would follow the code below:
max = arr[0]
max = arr[i]
To find the minimum number in an array, we would follow the code below:
min = arr[0]
for i in range (len(arr)):
min = arr[i]
a) del
The del function in a list deletes the element by index or slice, or removes the
entire list.
Example:
b) remove
The remove function in Python removes the first occurrence of a specified value
from a list.
Example:
c) sort
The sort function in Python sorts the elements of a list in ascending or descending
order, modifying the original list in place.
Example:
d) insert
Insert function in python helps to insert or add an extra element at the specified
index number.
Example:
e) pop
Pop function in python is used to remove and return the element at a specified
index from the list. If no index is mentioned, it removes the last element.
Example:
4. Consider a 2D matrix a = [[1, 2, 3], [4, 5, 6],[7, 8, 9]] What will be the result of
the following slicing operations?
a[0] - [1,2,3]
a[1][2] - 6
These functions are typically used with NumPy arrays and not regular python lists.
Here is a python code explaining all the above functions:
import numpy as np
# 5. reshape() - changes the shape of the matrix (reshaping into a 1D array here)
5. Define arrays in python. Write Python code to count the total no. of duplicate
elements in array, remove the duplicate elements from the array, return the
number which has maximum duplicate elements
Python also has a pre-defined module associated with arrays for more complex
uses. But for simple operations, we use lists.
arr = [1, 2, 3, 1, 4, 2, 5, 3, 1
count_elements = Counter(arr)
unique_elements = list(count_elements.keys())
The arrange() function in Numpy is used to create arrays with evenly spaced
values within a specified range
Example:
import numpy as np
print(arr) # Output: [1 3 5 7 9]
Example:
Alias:
View:
● A view creates a new array object that looks at the same data as the
original array.
● Changes in the view reflect in the original array, but their identities (objects)
are different.
Copy:
Example:
import numpy as np
# Original array
# Alias
# View
7. Write Python programs to remove duplicate values from the array [1, 3, 5, 7,
9, 9, 11, 13, 15, 17, 19, 19, 21, 23, 23]. using three different methods:
i)Basic looping
arr = [1,3,5,7,9,9,11,13,15,17,19,19,21,23,23]
for i in range(len(arr)-1,0,-1):
if arr[i] == arr[j]:
arr.pop(j)
break
print(arr)
data = [1,3,5,7,9,9,11,13,15,17,19,19,21,23,23]
unique_keys = []
for group in groupby(data):
unique_keys.append(group[0])
print(unique_keys)
data = [1,3,5,7,9,9,11,13,15,17,19,19,21,23,23]
unique_keys = list(dict.fromkeys(data))
print(unique_keys)
Examples:
● CREATE LIST:-
my_list = [1, 2, 3, 4, 5]
# Using list() constructor
● ACCESS AN ELEMENT:-
print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30
● SLICING LISTS:-
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
● MODIFYING LIST:-
my_list[2] = 100
● ADDING ELEMENTS:-
my_list = [1, 2, 3]
my_list.append(4)
my_list.insert(1, 10)
print(my_list) # Output: [1, 10, 2, 3, 4]
my_list.extend([5, 6, 7])
● REMOVING ELEMENTS:-
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
my_list.pop(1)
my_list.clear()
print(my_list) # Output: []
print(len(my_list)) # Output: 5
# Minimum element
print(min(my_list)) # Output: 10
# Maximum element
print(max(my_list)) # Output: 50
# Sum of elements
my_list.sort()
my_list.sort(reverse=True)
new_list = sorted(my_list)
● REVERSING A LIST:-
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
reversed_list = my_list[::-1]
● CHECKING MEMBERSHIP:-
my_list = [1, 2, 3, 4, 5]
print(nested_list[1][2]) # Output: 6
for i in d:
if i == key:
print("Key exists")
break
else:
nums = [0, 2, 8, 1, 3, 4, 9]
nums1 = []
for i in range(len(nums)):
nums1.append(nums[i])
num = [9,8,7,6,5,4,3,2,1]
k = len(num)
for j in range(k):
for i in range(0,k-j-1):
print(num)
12. Illustrate the type codes for defining arrays with an example python
program.
While using the array module, each array has a type code that specifies the type
of elements it can store. These type codes are single characters that represent
various data types (such as integers, floating-point numbers, etc.). The type code
is specified when creating an array.
import array
13. Write a program to count the number of times the letters ‘b’, ‘a’, and ‘n’
appear in the string 'banana', without using the count() function
str = "banana"
str_alphabet = []
count_b = 0
count_a = 0
count_n = 0
for i in range(len(str)):
str_alphabet.append(str[i])
for j in str_alphabet:
if j == 'b':
count_b +=1
elif j == 'a':
count_a +=1
else:
count_n +=1
import array
arr = [1,2,2,3,4,4,5]
for i in range(len(arr)-1,0,-1):
if arr[i] == arr[j]:
arr.pop(j)
break
print(arr)
15. Write a Python program to find the 3rd smallest number in the unsorted
array [7, 10, 4, 3, 20, 15].
import array
arr = [7,10,4,3,20,15]
for i in range(len(arr)):
for j in range(0,len(arr)-i-1):
17. Write a Python program to implement the stack and queue using list
operations.
● Stack Implementation using List
A stack is a collection of elements that follows the Last In, First Out (LIFO)
principle. Python’s list provides methods like append() to add an element to the
end and pop() to remove the element from the end, which makes it easy to
implement a stack.
Stack Operations:
Example:
class Stack:
def __init__(self):
self.stack = []
def pop(self):
if self.is_empty():
def peek(self):
if self.is_empty():
def is_empty(self):
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
A queue is a collection of elements that follows the First In, First Out (FIFO)
principle. In Python, lists provide the append() method to add elements at the end
and pop(0) to remove the element from the front, making it easy to implement a
queue. However, using pop(0) can be inefficient for large queues due to its O(n)
complexity.
Queue Operations:
Example:
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
def dequeue(self):
if self.is_empty():
def front(self):
if self.is_empty():
def is_empty(self):
def size(self):
queue = Queue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
18. Write a Python program to reverse the elements of an array without using
any in-built functions.
def reverse_array(arr):
start = 0
end = len(arr) - 1
start += 1
end -= 1
arr = [1, 2, 3, 4, 5, 6]
reverse_array(arr)
def flatten_array(arr):
flat_list = []
flat_list.extend(sublist)
return flat_list
flat_list = flatten_array(multi_dimensional_array)
20. You are managing a library system with two sections: Fiction and
Nonfiction. The registered members in these sections are as follows: Members in
Fiction Section: [‘Ajay’, ‘Babu’, ‘Charlie’, ‘David’, ‘Elizabeth’] Members in
Non-Fiction Section: [‘Charlie’, ‘David’, ‘Frank’, ‘Grace’, ‘Babu’] Using Python
sets, answer the following questions: Identify the members who registered in
both sections. List the members who registered in only one section (not both).
Determine if all members of the Fiction section also registered in the Non
Fiction section. Find the total number of unique members across both sections.
common = fiction.intersection(non_fiction)
#List the members who registered in only one section (not both).
separate = fiction.symmetric_difference(non_fiction)
subset = fiction.issubset(non_fiction)
total = fiction.union(non_fiction)
21. A university manages its student database using a dictionary. Each student
has a unique Student ID as the key, and their details (such as name, age,
courses enrolled, and GPA) are stored as a nested dictionary. You are required
to implement the following operations using dictionary methods: 1. Add or
Update a Student’s Information: If the student already exists, use setdefault()
to ensure that the courses and GPA have default values. 2. Check Student’s
Enrolment in a specific course using their Student ID. 3. List All Students with
their details (Student ID, Name, Age, Courses, GPA). 4. Retrieve a Student’s GPA
using their Student ID. 5. Update a Student’s Course List by adding or removing
a course. 6. Remove a Student from the database using their Student ID and
finally clear the Entire Student Database
student_db = {}
if student_id in student_db:
else:
return False
def list_all_students():
if not student_db:
else:
def get_gpa(student_id):
if student_id in student_db:
return student_db[student_id]["gpa"]
else:
return None
if student_id in student_db:
if add:
student_db[student_id]["courses"].append(course)
else:
try:
student_db[student_id]["courses"].remove(course)
except ValueError:
else:
def remove_student(student_id):
if student_id in student_db:
student_db.pop(student_id)
else:
print(f"Student {student_id} not found.")
def clear_database():
student_db.clear()
22. Write the algorithm and python implementation for the following Find the
kth maximum element of an array (4M) Find the kth minimum element of an
array (4M)
print("CREATING AN ARRAY")
arr = []
for i in range(0,num):
arr.append(a)
print(" ")
arr.sort()
print("CREATING AN ARRAY")
arr = []
for i in range(0,num):
arr.append(a)
print(" ")
def kth_minimum_element():
arr.sort()
kth_minimum_element()
#Write a python program to insert a newly created item ‘24’ before the
second element in an existing array. (2M)
def insert_an_item():
arr.insert(i,n)
insert_an_item()
def remove_the_first_10():
array = [4,9,10,9,3,8,5,10]
for i in range(len(array)):
if array[i]==10:
array.remove(10)
break
remove_the_first_10()
def two_smallest_and_largest_numbers():
arr = [95,25,75,35,65,45,85,55]
new_arr = []
k = len(arr)
for j in range(k):
for i in range(0,k-j-1):
new_arr.append(arr[0])
new_arr.append(arr[1])
new_arr.append(arr[-1])
new_arr.append(arr[-2])
two_smallest_and_largest_numbers()
24. A nested dictionary represents a stock maintenance of a mobile shop with
mobile name as keys and their details (like model, cost and product ID) as
another dictionary. Write a python program to: Add a new mobile to the
dictionary. Update the cost of an existing mobile. Display all mobile name and
their details.
mobile_shop = {}
if name in mobile_shop:
else:
if name in mobile_shop:
mobile_shop[name]["cost"] = new_cost
else:
def display_all_mobiles():
if not mobile_shop:
else:
print("Mobile Stock Details:")
# Example Usage
update_cost("iPhone", 85000)
display_all_mobiles()
SAME AS ANSWER 20
SAME AS ANSWER 14
my_set = {1, 2, 3}
my_list = [4, 5]
my_set.add(my_list)
● Yes, we can add a tuple as an element in a set. Since tuples are immutable
(their content cannot be changed after creation), they apply to the
conditions for being added to the set.
○ Example:
my_set = {1, 2, 3}
my_tuple = (4, 5)
my_set.add(my_tuple)
In Python, dictionaries are mutable objects, which means their contents can
change. Since sets require their elements to be hashable (i.e., their hash value
must be constant and unchanging), dictionaries, being mutable, are not hashable.
As a result, you cannot add a dictionary as an element of a set.
28. Write the output of the following Python Program: university=('V', 'I','T','B',
'h','o','p', 'a','l') #Tuple
print(university[-4]) : o
print(university[-2]) : a
print(university[-2:-6:1]) : ()
print(university[-10:-7:-1]) : ()
3. Access and print the first and last element of the tuple.
4. Change one of the numbers in the tuple (if tuples are immutable, how can
you still change it?) — show how to create a new tuple that reflects this change
without modifying the original tuple.
tup_list = []
for i in range(0,a):
tup_list.append(b)
tup = tuple(tup_list)
for i in range(len(tup_list)):
if tup_list[i] == n:
tup_list.remove(n)
tup_list.insert(i,k)
tup_list1 = tup_list
updated_tup = tuple(tup_list1)
30. Write a Python program to reverse the order of elements in a given list. Use
slicing to reverse the list efficiently.
def reverse_list(input_list):
return input_list[::-1]
original_list = [1, 2, 3, 4, 5]
reversed_list = reverse_list(original_list)
● Mutability
○ Lists are mutable: You can change the content (add, remove, modify
elements) after the list is created.
○ Tuples are immutable: Once a tuple is created, its elements cannot be
changed.
● Use cases
○ Lists are used when the values have to be updated after short
durations. Example- managing a collection of items
○ Tuples are used when the values have to be fixed after they are
stored and no changes should be done on it further. Example- setting
coordinates of a place.
● Memory efficiency
○ Lists are less memory-efficient because they store additional
overhead for dynamic resizing.
○ Tuples are more memory-efficient due to their immutability and fixed
size
● When Data Should Not Change: Example: Storing constants like days of the
week.
print(days_of_week)
def display_coordinates(coords):
● Improved Performance:
○ Tuples are faster to access compared to lists because of their
immutability.
32. In order to calculate the factorial of a non-negative integer without the use
of recursion or built in functions such as math.factorial(), write a Python
function. Your function should produce a solution with the ideal time complexity
and be able to handle huge input numbers with ease. Provide an example to
illustrate.
def factorial_iterative(n):
if n == 0:
return 1
result = 1
result *= i
return result
# Example usage
factorial_result = factorial_iterative(number)
33. A restaurant in a small town has a customer base of 150 regular diners.
Each day, about 30 different customers dine in, and the restaurant is open 25
days a month. You have a list of lists with the names of customers who dined in
each day over the past month. Find the unique customers to include them in a
loyalty program.
daily_customers = [
# Step 1: Flatten the list of lists into a single list of all customers
unique_customers = set(all_customers)
print(unique_customers)
34. Write a function find_index(), which returns the index of a number in the
Fibonacci sequence, if the number is an element of this sequence and returns-1
if the number is not contained in it, call this function using user input and
display the result
def find_index(num):
a, b = 0, 1
index = 0
if num == 0:
return 0
elif num == 1:
return 1
a, b = b, a + b
index += 1
if b == num:
return index + 1
return -1
if __name__ == "__main__":
try:
result = find_index(number)
if result == -1:
else:
except ValueError:
print(num) : (10,20,30,40,50,60,70,80,90,100)
print(num[1]) : 20
print(num[:0]) : ()
print(num[-4]) : 70
print(num[::4]) : (10,50,90)
print(num[-3:-8:1]) : ()
print(num[-3:-8:-1]) : (80,70,60,50,40)
print(num[-10:-6:-1]) : ()
print(num[-10:-6:1]) : (10,20,30,40)
print(num[-10:-6]) : (10,20,30,40)
print(num[0:]) : (10,20,30,40,50,60,70,80,90,100)
36. Write a Python program that takes two lists and prints all the common
elements of those two lists.
l1= []
for i in range(0,num1):
l1.append(a)
l2 = []
for j in range(0,num2):
l2.append(b)
37. What is the difference between list, set, tuple and dictionary in python?
1. List
● Definition: A list is an ordered, mutable (changeable) collection of elements
that can hold multiple items of any data type.
● Syntax: my_list = [1, 2, 3, 4, 5]
● Characteristics:
○ Ordered: The elements in a list have a defined order, and the order is
maintained.
○ Mutable: You can change elements, add or remove items after the list
is created.
○ Allows Duplicates: Lists can contain duplicate elements.
○ Indexed: Access elements via indices.
● Use Cases:
○ Storing a sequence of elements that might need to be modified.
○ Example: Storing shopping lists, student names, etc.
● Example:
my_list = [10, 20, 30, 40, 50]
2. Set
3. Tuple
print(my_tuple[1]) # Output: 20
4. Dictionary
38. Explain the below given terms with respect to 1-D array in python: 1.
Comparison operations 2. any () 3. all () 4.where ()
Example:
import numpy as np
The any() function checks whether any element of a 1-D array evaluates to True.
It returns a Boolean value: True if at least one element is True, and False if all
elements are False.
Syntax: numpy.any(array)
Example:
import numpy as np
result = np.any(arr)
The all() function checks whether all elements in the array evaluate to True. It
returns True if all elements are True, and False if at least one element is False.
Syntax: numpy.all(array)
Example:
import numpy as np
Example:
import numpy as np
39. Explain the different way to declare the list data structure in python. Also
explain the following list methods with an example. a) append () b) pop () c)
index() d) extend ()
a) append()
my_list.append(4)
b) pop()
● Description: Removes and returns the last element of the list by default. You
can also specify the index to remove an element from that position.
● Example:
my_list = [1, 2, 3, 4]
c) index()
print(index) # Output: 1
d) extend()
● Description: Adds all elements from another iterable (like a list, tuple, or
string) to the end of the current list.
● Example:
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
40. Implement the queue data structure with insert and delete operations using
tuple in python
temp_list = list(queue)
temp_list.append(element)
return tuple(temp_list)
def dequeue(queue):
"""Remove and return the first element of the queue."""
if len(queue) == 0:
temp_list = list(queue)
first_element = temp_list.pop(0)
# Example usage
# Insert elements
# Delete elements