Lists

This page contains the NCERT Computer Science class 11 chapter 9 Lists. You can find the solutions for the chapter 9 of NCERT class 11 Computer Science Exercise. So is the case if you are looking for NCERT class 11 Computer Science related topic Lists questions and answers for the Exercise
Exercise
1. What will be the output of the following statements?
i.
list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)
ii.
list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)
iii.
list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]
iv.
list1 = [1,2,3,4,5]
list1[len(list1)-1]

(i)
# Create a list of numbers
list1 = [12,32,65,26,80,10]
# sort() changes the list in-place
list1.sort()
# Print the updated list
print(list1)
Output
[10, 12, 26, 32, 65, 80]
Because `sort()` sorts the list in-place (changes the same list).
(ii)
# Create a list of numbers
list1 = [12,32,65,26,80,10]
# sorted() returns a new list; result is ignored here
sorted(list1)
# Original list remains unchanged
print(list1)
Output:
[12, 32, 65, 26, 80, 10]
Because `sorted(list1)` makes a new sorted list, but we did not store it, so `list1` remains unchanged.
(iii)
# List of 1 to 10
list1 = [1,2,3,4,5,6,7,8,9,10]
# Slice with step -2 (reverse, skip every other element)
list1[::-2]
# Join two slices to rebuild the full list
list1[:3] + list1[3:]
`list1[::-2]` gives:
[10, 8, 6, 4, 2]
`list1[:3] + list1[3:]` gives:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(These are expressions. In a normal program, they won’t print unless we use `print()`.)
(iv)
# List of five elements
list1 = [1,2,3,4,5]
# Access the last element using length - 1
list1[len(list1)-1]
Output:
5
Because `len(list1)` is 5, so index is `5-1 = 4`, and `list1[4] = 5`.
2. Consider the following list myList. What will be the elements of myList after the following two operations:
myList = [10,20,30,40]
i.
myList.append([50,60])
ii.
myList.extend([80,90])
myList = [10,20,30,40]

myList.append([50,60])
print(myList)

myList.extend([80,90])
print(myList)
i. After myList.append([50,60])
Output:
[10, 20, 30, 40, [50, 60]]
(`append()` adds the whole list as one element, so it becomes a nested list.)
ii. After `myList.extend([80,90])`:
Output:
[10, 20, 30, 40, [50, 60], 80, 90]
(`extend()` adds each element one by one.)
3. What will be the output of the following code segment:
myList = [1,2,3,4,5,6,7,8,9,10]
    # Loop over all indices
    for i in range(0,len(myList)):
        # Print elements at even indices
        if i%2 == 0:
            print(myList[i])
Output:
1
3
5
7
9
Because it prints elements at even indices: 0,2,4,6,8.
4. What will be the output of the following code segment:
a.
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
b.
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
c.
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)
(a)
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
Output:
[1, 2, 3]
Explanation: Deletes elements from index 3 onward, leaving only the first three items.
(b)
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
Output:
[6, 7, 8, 9, 10]
Explanation: Removes the first five elements, so only elements from index 5 onward remain.
(c)
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)
Output:
[2, 4, 6, 8, 10]
Explanation: Deletes every element at even indices (0, 2, 4, 6, 8).
Because `del myList[::2]` removes elements at indices 0,2,4,6,8 → (1,3,5,7,9 removed).
5. Differentiate between `append()` and `extend()` functions of list.
Point of difference
append()
extend()
What it adds
Adds one single element at the end of the list
Adds multiple elements (from another list/iterable) to the end
If we pass a list
The whole list is added as one item (nested list)
Each item of the list is added one by one
Effect on list size
Size increases by 1
Size increases by the number of elements added
Example (with output)
# Demonstrating append() vs extend()

myList = [10, 20, 30, 40]

# append(): adds the whole list as ONE element (nested list)
myList.append([50, 60])
print("After append([50, 60]) :", myList)

# extend(): adds elements one by one
myList.extend([80, 90])
print("After extend([80, 90]) :", myList)
Sample Output:
After append([50, 60]) : [10, 20, 30, 40, [50, 60]]
After extend([80, 90]) : [10, 20, 30, 40, [50, 60], 80, 90]
Conclusion:
We should use `append()` when we want to add a single item (even if that item is another list).
We should use `extend()` when we want to add all elements of another list/iterable into the same list.
6. Consider a list:
list1 = [6,7,8,9]
What is the difference between the following operations on list1:
a.
list1 * 2
b.
list1 *= 2
c.
list1 = list1 * 2
(a) `list1 * 2`
Creates a new list (does not change original unless assigned):
# Original list
list1 = [6,7,8,9]
# Multiply creates a new list (no assignment here)
print(list1 * 2)
Sample Output:
[6, 7, 8, 9, 6, 7, 8, 9]
Explanation:
Multiplication returns a new repeated list; the original list changes only if assigned.
(b) `list1 *= 2`
Repeats and modifies the same list in-place (original list changes): list1 becomes
# Original list
list1 = [6,7,8,9]
# In-place repeat modifies the same list
list1 *= 2
# list1 now contains repeated elements
print(list1)
Sample Output:
[6, 7, 8, 9, 6, 7, 8, 9]
Explanation:
The list is modified in-place, so list1 itself becomes the repeated list.
(c) `list1 = list1 * 2`
Creates a new list and then `list1` starts referring to it.
Looks same as (b) in values, but it’s a new object (important if another variable was pointing to the old list).
# Original list
list1 = [6,7,8,9]
# Create a new list and reassign list1
list1 = list1 * 2
# list1 now refers to the new list
print(list1)
Sample Output:
[6, 7, 8, 9, 6, 7, 8, 9]
Explanation:
A new list is created and assigned back to list1, replacing the old one.
7. The record of a student (Name, Roll No., Marks in five subjects and percentage of marks) is stored in the following list:
stRecord = ['Raman','A-36',[56,98,99,72,69], 78.8]
Write Python statements to retrieve the following information from the list stRecord.
a)
Percentage of the student
b)
Marks in the fifth subject
c)
Maximum marks of the student
d)
Roll no. of the student
e)
Change the name of the student from ‘Raman’ to ‘Raghav’
Python statements (pointwise):
(a) Percentage of the student
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]
# Percentage is stored at index 3
print("Percentage =", stRecord[3])
Sample Output:
Percentage = 78.8
Explanation:
Index 3 holds the percentage value in the record.
(b) Marks in the fifth subject
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]
# Marks list is at index 2; fifth subject is index 4
print("Marks in 5th subject =", stRecord[2][4])
Sample Output:
Marks in 5th subject = 69
Explanation:
The marks list is nested at index 2, so subject 5 is at index 4.
(c) Maximum marks of the student
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]
# max() finds the highest mark in the marks list
print("Maximum marks =", max(stRecord[2]))
Sample Output:
Maximum marks = 99
Explanation:
max() is applied to the marks list at index 2.
(d) Roll no. of the student
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]
# Roll number is stored at index 1
print("Roll No. =", stRecord[1])
Sample Output:
Roll No. = A-36
Explanation:
Index 1 contains the roll number string.
(e) Change the name from Raman to Raghav
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]
# Name is stored at index 0
stRecord[0] = 'Raghav'
print("Updated record =", stRecord)
Sample Output:
Updated record = ['Raghav', 'A-36', [56, 98, 99, 72, 69], 78.8]
Explanation:
Updating index 0 replaces the student name in the list.
Programming Problems
1. Write a program to find the number of times an element occurs in the list.
# Program 1: Count occurrences of an element in a list

# Read list size
n = int(input("How many elements do you want to enter? "))

# Create an empty list and take inputs
numbers = []
for i in range(n):
    val = int(input("Enter element " + str(i + 1) + ": "))
    numbers.append(val) # append() adds one element at the end

# Input the element to count
target = int(input("Enter the element to count: "))

# Count occurrences (manual method using traversing)
# Start count at zero and update when match found
count = 0 for item in numbers:
    if item == target:
        count += 1

# Display results
print("List:", numbers)
print(str(target) + " occurs " + str(count) + " time(s) in the list.")
Sample Output:
How many elements do you want to enter? 5
Enter element 1: 2
Enter element 2: 4
Enter element 3: 2
Enter element 4: 6
Enter element 5: 2
Enter the element to count: 2
List: [2, 4, 2, 6, 2]
2 occurs 3 time(s) in the list.
2. Write a program to read a list of n integers (positive as well as negative). Create two new lists, one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.
# Program 2: Separate positive and negative numbers

n = int(input("How many integers do you want to enter? "))

# Lists to store original and separated values
main_list = []
positive_list = []
negative_list = []

for i in range(n):
    num = int(input("Enter integer " + str(i + 1) + ": "))
    main_list.append(num)

    # Put number in correct list
    if num >= 0:
        positive_list.append(num)
    else:
        negative_list.append(num)
# Display all three lists
print("Original list:", main_list)
print("Positive list:", positive_list)
print("Negative list:", negative_list)
Sample Output:
How many integers do you want to enter? 6
Enter integer 1: -4
Enter integer 2: 0
Enter integer 3: 7
Enter integer 4: -1
Enter integer 5: 5
Enter integer 6: -9
Original list: [-4, 0, 7, -1, 5, -9]
Positive list: [0, 7, 5]
Negative list: [-4, -1, -9]
3. Write a function that returns the largest element of the list passed as parameter.
# Program 3: Function to return the largest element

def largest_element(lst):
    """
    Returns the largest element from the list 'lst'.
    Assumes lst is not empty.
    """
    # Start by assuming the first element is the largest
    largest = lst[0]

    # Traverse the list to find the largest
    for item in lst:
        if item > largest:
            largest = item

    return largest

# ---- Main code ----
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
    # Read each element and add to list
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))

# Call the function and print the result
print("Largest element:", largest_element(lst))
Sample Output:
Enter number of elements: 5
Enter element 1: 12
Enter element 2: 7
Enter element 3: 25
Enter element 4: 3
Enter element 5: 18
Largest element: 25
4. Write a function to return the second largest number from a list of numbers.
# Program 4: Function to return the second largest element

def second_largest(lst):
    """
    Returns the second largest number in the list.
    Assumes list has at least 2 distinct elements.
    """
    # Remove duplicates by converting to a set, then back to list
    unique = list(set(lst))

    # Sort the unique list in descending order
    unique.sort(reverse=True)

    # Second element is the second largest
    return unique[1]

# ---- Main code ----
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))

if len(set(lst)) < 2:
    # Need at least two distinct values for a second largest
    print("Second largest not possible (need at least 2 distinct values).")
else:
    print("Second largest:", second_largest(lst))
Sample Output:
Enter number of elements: 5
Enter element 1: 12
Enter element 2: 7
Enter element 3: 25
Enter element 4: 3
Enter element 5: 18
Second largest: 18
5. Write a program to read a list of n integers and find their median.
Note: The median value of a list of values is the middle one when they are arranged in order. If there are two middle values then take their average.
Hint: You can use an built-in function to sort the list
# Program 5: Median of a list
# Median = middle value after sorting
# If even count, median = average of two middle values

def median(lst):
    """
    Returns the median of the list lst.
    """
    sorted_list = sorted(lst) # sorted() returns a new sorted list
    n = len(sorted_list)

    mid = n // 2

    # If n is odd, one middle element
    if n % 2 == 1:
        return sorted_list[mid]

    # If n is even, average of two middle elements
    return (sorted_list[mid - 1] + sorted_list[mid]) / 2

# ---- Main code ----
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))

# Show sorted list and its median
print("Sorted list:", sorted(lst))
print("Median:", median(lst))
Sample Output:
Enter number of elements: 5
Enter element 1: 12
Enter element 2: 7
Enter element 3: 25
Enter element 4: 3
Enter element 5: 18
Sorted list: [3, 7, 12, 18, 25]
Median: 12
6. Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all elements occurring multiple times in the list should appear only once.
# Program 6: Remove duplicates (keeping first occurrence)

n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))

# Build a new list with only first occurrences
unique = []
for item in lst: # membership operator 'in' checks if item is already present
    if item not in unique:
        unique.append(item)

# Print both lists for comparison
print("Original list:", lst)
print("List without duplicates:", unique)
Sample Output:
Enter number of elements: 6
Enter element 1: 2
Enter element 2: 4
Enter element 3: 2
Enter element 4: 5
Enter element 5: 4
Enter element 6: 7
Original list: [2, 4, 2, 5, 4, 7]
List without duplicates: [2, 4, 5, 7]
7. Write a program to read a list of elements. Input an element from the user that has to be inserted in the list. Also input the position at which it is to be inserted. Write a user defined function to insert the element at the desired position in the list.
# Program 7: Insert element at desired position using a function
    
def insert_at_position(lst, element, pos):
    """
    Inserts 'element' at index 'pos' in list lst using insert().
    If pos is out of range, it will insert at the nearest valid place.
    """
    if pos < 0:
        pos = 0
    if pos > len(lst):
        pos = len(lst)

    lst.insert(pos, element)  # insert(index, value)

# ---- Main code ----
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))

element = int(input("Enter the element to insert: "))
pos = int(input("Enter the position (0-based index): "))

# Perform the insertion
insert_at_position(lst, element, pos)

# Show updated list
print("Updated list:", lst)
Sample Output:
Enter number of elements: 4
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter the element to insert: 25
Enter the position (0-based index): 2
Updated list: [10, 20, 25, 30, 40]
8. Write a program to read elements of a list.
a)
The program should ask for the position of the element to be deleted from the list. Write a function to delete the element at the desired position in the list.
b)
The program should ask for the value of the element to be deleted from the list. Write a function to delete the element of this value from the list.
# Program 8: Delete by position and by value using functions

def delete_by_position(lst, pos):
    """
    Deletes the element at index 'pos' using pop().
    Returns deleted element, or None if position is invalid.
    """
    if 0 <= pos < len(lst):
        return lst.pop(pos) # pop(index) removes and returns element
    return None

def delete_by_value(lst, value):
    """
    Deletes the first occurrence of 'value' using remove().
    Returns True if deleted, else False.
    """
    if value in lst:
        lst.remove(value) # remove(value) deletes first occurrence
        return True
    return False

# ---- Main code ----
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))

print("Original list:", lst)

# (a) Delete by position
pos = int(input("Enter position (0-based) to delete: "))
deleted = delete_by_position(lst, pos)
if deleted is None:
    print("Invalid position! No deletion done.")
else:
    print("Deleted element:", deleted)
    print("List after deleting by position:", lst)

# (b) Delete by value
value = int(input("Enter value to delete: "))
ok = delete_by_value(lst, value)
if not ok:
    print("Value not found! No deletion done.")
else:
    print("List after deleting by value:", lst)
Sample Output:
Enter number of elements: 5
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Original list: [10, 20, 30, 40, 50]
Enter position (0-based) to delete: 2
Deleted element: 30
List after deleting by position: [10, 20, 40, 50]
Enter value to delete: 50
List after deleting by value: [10, 20, 40]
9. Read a list of n elements. Pass this list to a function which reverses this list in-place without creating a new list.
# Program 9: Reverse a list in-place (without creating a new list)

def reverse_in_place(lst):
    """
    Reverses the list in-place using swapping.
    This does NOT create a new list.
    """
    left = 0
    right = len(lst) - 1

    while left < right:
        # Swap elements at left and right
        lst[left], lst[right] = lst[right], lst[left]
        left += 1
        right -= 1

# ---- Main code ----
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
    lst.append(int(input("Enter element " + str(i + 1) + ": ")))

print("Original list:", lst)
reverse_in_place(lst)
print("Reversed list:", lst)
Sample Output:
Enter number of elements: 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]