Linear List Manipulation

This page contains the CBSE Computer Science with Python class 12 Unit-2 chapter 1 Linear List Manipulation. You can find the solutions for chapter 1 of CBSE class 12 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 12 Computer Science with Python related topic Linear List Manipulation questions and answers for the Exercise.
Exercise
Question 1
1. Define a data structure.
Answer 1
A data structure is a way of organising and storing data in a computer so that it can be accessed, processed and modified efficiently.
It is basically a group of related data items that can be handled as a single unit in a program.
For example, a list is a data structure because it stores many values together and we can perform operations like insertion, deletion, searching and sorting on it.
Question 2
2. Name the two types of data structures and give one point of difference between them.
Answer 2
The two types of data structures are:
1.
Linear data structure
2.
Non-linear data structure
In a linear data structure, elements are arranged in a sequence (one after another), so traversal is done in a straight order.
In a non-linear data structure, elements are not arranged in one straight line; they form levels/branches, so there is no single sequential order.
Difference:
Basis
Linear Data Structure
Non-linear Data Structure
Arrangement of elements
Elements are stored in sequential order (one after another).
Elements are stored without sequential order (may be in branches/levels).
Traversal
Traversal is generally from first to last in sequence.
Traversal can follow multiple paths (not one fixed sequence).
Example (for understanding)
List, Stack, Queue
Tree, Graph
Question 3
3. Give one point of difference between an array and a list in Python.
Answer 3
In Python, an array (in general concept) stores elements of similar data type and is usually stored as contiguous data.
Whereas a Python list is like an array of variable length and it can store different types of elements (heterogeneous), such as integers, strings, and floats together.
Difference:
Basis
Array
Python List
Type of elements
Stores similar data type elements.
Can store different data types together.
Length
Usually considered fixed size.
Variable length (can grow/shrink).
Nature
Stores contiguous data (concept of array).
Stores references and behaves like a dynamic array of references.
Question 4
4. How are lists implemented in memory?
Answer 4
In Python, a list is implemented in memory as a contiguous array of references (pointers).
This means:
The list does not store the actual values directly in one block; instead it stores references (addresses) that point to the actual objects (like integer objects, string objects, etc.).
Because it is a contiguous array of references, Python can access an element quickly using its index (like L[0], L[1], etc.).
Also, Python lists are of variable length, so when we add more items and the current space is not enough, Python creates a bigger array and shifts the references to the new place (so the list can grow).
Question 5
5. What is sequential allocation of memory? Why do we say that lists are stored sequentially?
Answer 5
Sequential allocation of memory means memory is allocated to elements in such a way that they are stored one after another in a sequence (in the order of their declaration).
We say that lists are stored sequentially because:
The elements of a list are arranged in a linear order (first element, second element, third element, and so on).
When we traverse a list, we move sequentially from the first element to the last element.
So, a list behaves as a linear data structure where data is accessed in a proper sequence.
Question 6
6. How is memory allocated to a list in Python?
Answer 6
In Python, memory for a list is allocated using a contiguous array of references (pointers). This means the list stores addresses (references) of the elements, and not the actual objects directly.
Also, Python lists are dynamic (variable length). So:
When we create a list, Python allocates memory for a certain number of references.
If we add more elements and the list needs more space, Python automatically allocates a bigger block of memory and shifts the references so the list can grow.
The book also mentions that the memory requirement depends on:
Number of elements in the list
Size of a pointer/reference (for example, 4 bytes in a 32-bit system and 8 bytes in a 64-bit system).
Question 7
7. Write a function that takes a list that is sorted in ascending order and a number as arguments. The function should do the following:
a.
Insert the number passed as argument in a sorted list.
b.
Delete the number from the list.
Answer 7
Python Program
# Program: Insert and Delete in a sorted list (Python 2)

def insert_sorted(data_list, num):
    # Insert num at correct position to keep ascending order
    pos = 0
    while pos < len(data_list) and data_list[pos] < num:
        pos = pos + 1
    data_list.insert(pos, num)

def delete_number(data_list, num):
    # Delete first occurrence of num if found
    if num in data_list:
        data_list.remove(num)
        return True
    return False

# ---- main part ----
raw = raw_input("Enter sorted numbers (space separated): ")
lst = []
for x in raw.split():
    lst.append(int(x))

print "Original list:", lst

n = int(raw_input("Enter a number to insert: "))
insert_sorted(lst, n)
print "After insertion:", lst

m = int(raw_input("Enter a number to delete: "))
found = delete_number(lst, m)
if found:
    print "After deletion:", lst
else:
    print "Number not found, list unchanged:", lst
Sample Output:
# sample output
Enter sorted numbers (space separated): 2 5 9 15 20
Original list: [2, 5, 9, 15, 20]
Enter a number to insert: 10
After insertion: [2, 5, 9, 10, 15, 20]
Enter a number to delete: 5
After deletion: [2, 9, 10, 15, 20]
Question 8
8. How is linear search different from binary search?
Answer 8
Basis
Linear Search
Binary Search
Method / Approach
Checks elements one by one from beginning to end.
Checks the middle element and repeatedly halves the search range.
Data requirement
Can be used on unsorted or sorted lists.
Requires the list to be sorted.
Time complexity
O(n)
O(log n)
Comparisons (typical)
May compare with many elements (up to all).
Needs fewer comparisons for large lists.
Suitable use case
Small lists or unsorted data.
Large sorted lists with fast index access.
Question 9
9. Accept a list containing integers randomly. Accept any number and display the position at which the number is found is the list.
Answer 9
Python Program (linear search)
# Program: Find position of a number in a list using Linear Search (Python 2)

def linear_search(lst, key):
    # Returns index if found, else -1
    for i in range(len(lst)):
        if lst[i] == key:
            return i
    return -1

raw = raw_input("Enter integers (space separated): ")
nums = []
# Build the list from user input
for p in raw.split():
    nums.append(int(p))

print "List:", nums

key = int(raw_input("Enter number to search: "))
# Call linear search function
pos = linear_search(nums, key)

# Display result based on returned index
if pos != -1:
    print "Number found at position (index):", pos
else:
    print "Number not found."
Sample Output:
# sample output
Enter integers (space separated): 12 4 99 15 7 4
List: [12, 4, 99, 15, 7, 4]
Enter number to search: 15
Number found at position (index): 3
Sample Output 2:
# sample output (number not present)
Enter integers (space separated): 8 21 34 55 89
List: [8, 21, 34, 55, 89]
Enter number to search: 50
Number not found.
Question 10
10. Write a function that takes a sorted list and a number as an argument. Search for the number in the sorted list using binary search.
Answer 10
# Program: Binary Search in a sorted list (Python 2)

def binary_search(lst, key):
    # Set initial search boundaries
    low = 0
    high = len(lst) - 1

    # Continue while valid search range exists
    while low <= high:
        mid = (low + high) / 2  # integer division in Python 2
        if lst[mid] == key:
            # Key found at index mid
            return mid
        elif key < lst[mid]:
            # Search in left half
            high = mid - 1
        else:
            # Search in right half
            low = mid + 1
    # Key not found
    return -1

# Given sorted list
sorted_list = [2, 5, 9, 10, 15, 20]
print "Sorted list:", sorted_list

k = input("Enter number to search: ")
# Call binary search function
pos = binary_search(sorted_list, k)

# Display final result
if pos != -1:
    print "Found at index:", pos
else:
    print "Not found."
Sample Output:
# sample output
Sorted list: [2, 5, 9, 10, 15, 20]
Enter number to search: 10
Found at index: 3
Question 11
11. In the following list containing integers, sort the list using Insertion sort algorithm. Also show the status of the list after each iteration.
15 -520-1010
Answer 11
Insertion Sort arranges the list by taking the next element and inserting it into the correct position in the sorted part.
Initial list: [15, -5, 20, -10, 10]
Status after each iteration:
1.
After 1st iteration: [-5, 15, 20, -10, 10]
2.
After 2nd iteration: [-5, 15, 20, -10, 10]
3.
After 3rd iteration: [-10, -5, 15, 20, 10]
4.
After 4th iteration: [-10, -5, 10, 15, 20]
Question 12
12. Consider the following unsorted list
Neena MeetaGeetaReetaSeeta
Sort the list using selection sort algorithm. Show the status of the list after every iteration.
Answer 12
Selection sort repeatedly selects the smallest element from unsorted part and swaps it to correct position.
Initial: [Neena, Meeta, Geeta, Reeta, Seeta]
Iteration-wise status:
1.
After 1st iteration: [Geeta, Meeta, Neena, Reeta, Seeta]
2.
After 2nd iteration: [Geeta, Meeta, Neena, Reeta, Seeta] (no swap needed)
3.
After 3rd iteration: [Geeta, Meeta, Neena, Reeta, Seeta] (no swap needed)
4.
After 4th iteration: [Geeta, Meeta, Neena, Reeta, Seeta] (no swap needed)
Question 13
13. Consider the following unsorted list
90 782046541
Write the list after:
a.
3rd iteration of selection sort
b.
4th iteration of bubble ort
c.
5th iteration of insertion sort
Answer 13
Assumption: sorting is in ascending order.
Part
Step
Resulting List
(a)
After 3rd iteration of selection sort
[1, 20, 46, 78, 54, 90]
(b)
After 4th iteration of bubble sort
[20, 1, 46, 54, 78, 90]
(c)
After 5th iteration of insertion sort
[1, 20, 46, 54, 78, 90]
Question 14
14. Consider the following unsorted list:
105551334936
Write the position of elements in the list after:
a.
5th iteration of bubble sort
b.
7th iteration of insertion sort
c.
4th iteration of selection sort
Answer 14
(a) 5th iteration of bubble sort
[3, 5, 10, 13, 36, 49, 55]
(b) 7th iteration of insertion sort
For 7 elements, insertion sort completes in 6 outer iterations (but the final state remains the sorted list).
[3, 5, 10, 13, 36, 49, 55]
(c) 4th iteration of selection sort
[3, 5, 10, 13, 55, 49, 36]
Question 15
15. Sort a list containing names of students in ascending order using selection sort.
Answer 15
# Program: Selection Sort for names (Python 2)

def selection_sort_names(lst):
    # Sort list of names in ascending order using selection sort
    n = len(lst)
    # Fix one position at a time
    for i in range(n - 1):
        min_i = i
        # Find index of smallest name in remaining unsorted part
        for j in range(i + 1, n):
            if lst[j] < lst[min_i]:
                min_i = j
        # swap
        temp = lst[i]
        lst[i] = lst[min_i]
        lst[min_i] = temp

# Read names and create list
raw = raw_input("Enter student names (space separated): ")
names = raw.split()
print "Original:", names

# Sort and display result
selection_sort_names(names)
print "Sorted:", names
Sample Output:
# sample output
Enter student names (space separated): Riya Aman Neha Kabir
Original: ['Riya', 'Aman', 'Neha', 'Kabir']
Sorted: ['Aman', 'Kabir', 'Neha', 'Riya']
Question 16
16. A list contains roll_no, name and marks of the student. Sort the list in descending order of marks using Selection Sort algorithm.
Answer 16
# Program: Selection Sort by marks (descending) - Python 2

def selection_sort_by_marks_desc(lst):
    # Each record format: [roll_no, name, marks]
    n = len(lst)
    # Place highest marks at position i in each pass
    for i in range(n - 1):
        max_i = i
        # Find index of maximum marks in unsorted part
        for j in range(i + 1, n):
            # Compare marks (index 2)
            if lst[j][2] > lst[max_i][2]:
                max_i = j
        # swap current element with maximum-marks element
        temp = lst[i]
        lst[i] = lst[max_i]
        lst[max_i] = temp

students = []
n = int(raw_input("Enter number of students: "))
# Read all student records
for i in range(n):
    print "Enter student", i + 1
    roll = int(raw_input("Roll no: "))
    name = raw_input("Name: ")
    marks = int(raw_input("Marks: "))
    students.append([roll, name, marks])

print "Original:", students
# Sort records by marks in descending order
selection_sort_by_marks_desc(students)
print "Sorted by marks (desc):", students
Sample Output:
# sample output
Enter number of students: 4
Enter student 1
Roll no: 1
Name: Aman
Marks: 78
Enter student 2
Roll no: 2
Name: Neha
Marks: 92
Enter student 3
Roll no: 3
Name: Kabir
Marks: 65
Enter student 4
Roll no: 4
Name: Riya
Marks: 92
Original: [[1, 'Aman', 78], [2, 'Neha', 92], [3, 'Kabir', 65], [4, 'Riya', 92]]
Sorted by marks (desc): [[2, 'Neha', 92], [4, 'Riya', 92], [1, 'Aman', 78], [3, 'Kabir', 65]]
Question 17
17. A list contains Item_code, Item_name and price. Sort the list :
a.
In ascending order of price using Bubble sort.
b.
In descending order of qty using Insertion sort.
Answer 17
(a) Ascending order of price using Bubble sort
(b) Descending order of qty using Insertion sort
# Program: Bubble sort by price (asc) and Insertion sort by qty (desc) - Python 2

def bubble_sort_price_asc(items):
    # Sort items in ascending order of price (index 2)
    n = len(items)
    for i in range(n - 1):
        for j in range(0, n - 1 - i):
            # Compare adjacent prices
            if items[j][2] > items[j + 1][2]:
                temp = items[j]
                items[j] = items[j + 1]
                items[j + 1] = temp

def insertion_sort_qty_desc(items):
    # Sort items in descending order of quantity (index 3)
    for k in range(1, len(items)):
        temp = items[k]
        ptr = k - 1
        # descending by qty => move smaller qty to right
        while ptr >= 0 and items[ptr][3] < temp[3]:
            items[ptr + 1] = items[ptr]
            ptr = ptr - 1
        items[ptr + 1] = temp

items = []
n = int(raw_input("Enter number of items: "))
# Each record format: [item_code, item_name, price, qty]
for i in range(n):
    print "Enter item", i + 1
    Item_code = raw_input("Item code: ")
    Item_name = raw_input("Item name: ")
    price = int(raw_input("Price: "))
    qty = int(raw_input("Qty: "))
    items.append([Item_code, Item_name, price, qty])

print "Original:", items
# Part (a): sort by price in ascending order
bubble_sort_price_asc(items)
print "Sorted by price (asc):", items
# Part (b): sort by quantity in descending order
insertion_sort_qty_desc(items)
print "Sorted by qty (desc):", items
Sample Output:
# sample output
Enter number of items: 4
Enter item 1
Item code: I01
Item name: Pen
Price: 10
Qty: 50
Enter item 2
Item code: I02
Item name: Notebook
Price: 60
Qty: 25
Enter item 3
Item code: I03
Item name: Pencil
Price: 5
Qty: 100
Enter item 4
Item code: I04
Item name: Eraser
Price: 8
Qty: 80
Original: [['I01', 'Pen', 10, 50], ['I02', 'Notebook', 60, 25], ['I03', 'Pencil', 5, 100], ['I04', 'Eraser', 8, 80]]
Sorted by price (asc): [['I03', 'Pencil', 5, 100], ['I04', 'Eraser', 8, 80], ['I01', 'Pen', 10, 50], ['I02', 'Notebook', 60, 25]]
Sorted by qty (desc): [['I03', 'Pencil', 5, 100], ['I04', 'Eraser', 8, 80], ['I01', 'Pen', 10, 50], ['I02', 'Notebook', 60, 25]]
Question 18
18. Accept a list containing numbers. Sort the list using any sorting technique. Thereafter accept a number and display the position where that number is found. Also display suitable message, if the number is not found in the list.
Answer 18
# Program: Sort list and find number position (Python 2)

def selection_sort(lst):
    # Sort list in ascending order using selection sort
    n = len(lst)
    # Fix one position at a time
    for i in range(n - 1):
        min_i = i
        # Find index of smallest element in unsorted part
        for j in range(i + 1, n):
            if lst[j] < lst[min_i]:
                min_i = j
        # swap current element with smallest element found
        temp = lst[i]
        lst[i] = lst[min_i]
        lst[min_i] = temp

def binary_search(lst, key):
    # Set search boundaries
    low = 0
    high = len(lst) - 1
    # Search while valid range exists
    while low <= high:
        mid = (low + high) / 2
        if lst[mid] == key:
            # key found
            return mid
        elif key < lst[mid]:
            # key may be in left half
            high = mid - 1
        else:
            # key may be in right half
            low = mid + 1
    # key not found
    return -1

# Read list of numbers from user
raw = raw_input("Enter numbers (space separated): ")
nums = []
for p in raw.split():
    nums.append(int(p))

print "Original:", nums
# Sort before binary search
selection_sort(nums)
print "Sorted:", nums

k = int(raw_input("Enter number to search: "))
# Find position using binary search
pos = binary_search(nums, k)

# Display suitable message
if pos != -1:
    print "Number found at index:", pos
else:
    print "Number not found in the list."
Sample Output:
# sample output
Enter numbers (space separated): 9 2 15 1 10
Original: [9, 2, 15, 1, 10]
Sorted: [1, 2, 9, 10, 15]
Enter number to search: 10
Number found at index: 3
# sample output (number not found)
Enter numbers (space separated): 14 7 3 22 9
Original: [14, 7, 3, 22, 9]
Sorted: [3, 7, 9, 14, 22]
Enter number to search: 11
Number not found in the list.