CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Chapter 9: Lists
Complete, student-friendly notes based on the uploaded NCERT Reprint 2026–27 chapter. Includes clear concepts, syntax, worked examples, built-in methods, textbook programs, dry runs, solved exercises and additional programming solutions.
Chapter overview
A Python list is an ordered, mutable collection. It can store values of the same or different data types, and it can even contain another list. Lists are used to store related data such as student marks, product prices, names, temperatures and records.
Source reviewed: uploaded NCERT Class XI Computer Science, Chapter 9 “Lists”, Reprint 2026–27, 18 PDF pages (printed pages 189–206). The list-method table on printed pages 193–195 and program/output examples on printed pages 197–203 have been incorporated.
9.1 Introduction to List
A list is an ordered sequence that is mutable and contains one or more elements. “Ordered” means that elements retain their positions. “Mutable” means that elements can be changed after the list is created.
- List elements are enclosed in square brackets
[ ]. - Elements are separated by commas.
- List indexing starts from
0. - A list can contain integers, floats, strings, tuples, or even other lists.
- A list can contain mixed data types.
Syntax
list_name = [element1, element2, element3, ...]
Examples (Example 9.1)
# A list of six even numbers
list1 = [2, 4, 6, 8, 10, 12]
print(list1)
# [2, 4, 6, 8, 10, 12]
# A list of vowels
list2 = ['a', 'e', 'i', 'o', 'u']
print(list2)
# ['a', 'e', 'i', 'o', 'u']
# A list containing mixed data types
list3 = [100, 23.5, 'Hello']
print(list3)
# [100, 23.5, 'Hello']
# A nested list: each inner list stores a subject and code
list4 = [['Physics', 101], ['Chemistry', 202], ['Maths', 303]]
print(list4)
# [['Physics', 101], ['Chemistry', 202], ['Maths', 303]]
[] or list().9.1.1 Accessing Elements in a List
List elements are accessed in the same way as string characters: write the index inside square brackets.
Positive and negative indexing
Positive indexing begins at 0 from the left. Negative indexing begins at -1 from the right.
| Element | 2 | 4 | 6 | 8 | 10 | 12 |
|---|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
list1 = [2, 4, 6, 8, 10, 12]
print(list1[0]) # 2: first element
print(list1[3]) # 8: fourth element
print(list1[-1]) # 12: last element
print(list1[-6]) # 2: first element
print(list1[1+4]) # 12: index expression evaluates to 5
Accessing an index outside the valid range raises IndexError. For example, list1[15] is invalid for a six-element list.
Using len() to find the number of elements
The built-in len() function returns the total number of elements in a list.
list1 = [2, 4, 6, 8, 10, 12]
n = len(list1)
print(n) # 6
print(list1[n-1]) # 12: last element
print(list1[-n]) # 2: first elementn, valid positive indices are 0 through n-1; valid negative indices are -n through -1.9.1.2 Lists are Mutable
Lists are mutable, which means that their elements can be modified after the list has been created. Assign a new value to a particular index.
Syntax
list_name[index] = new_valueExample
list1 = ['Red', 'Green', 'Blue', 'Orange']
# Change the fourth element (index 3)
list1[3] = 'Black'
print(list1)
# ['Red', 'Green', 'Blue', 'Black']Only the element at index 3 is replaced. The other elements remain unchanged.
list1[0] = 99, but you cannot assign a character using text[0] = 'A'.9.2 List Operations
Python provides operators to combine lists, repeat their contents, test membership and extract a portion of a list.
9.2.1 Concatenation
Concatenation joins two or more lists. The + operator places the elements of the second list after the elements of the first list.
Syntax
new_list = list1 + list2Example
# First five odd integers
list1 = [1, 3, 5, 7, 9]
# First five even integers
list2 = [2, 4, 6, 8, 10]
list3 = list1 + list2
print(list3)
# [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]Concatenation creates a new list; it does not change the original lists unless the result is assigned back.
list1 = [1, 2, 3]
str1 = "abc"
print(list1 + str1)
# TypeError: can only concatenate list (not "str") to list+ must be lists. A list cannot be concatenated directly with a string or another non-list value.9.2.2 Repetition
The repetition operator * replicates a list a specified number of times.
Syntax
new_list = list_name * numberExample
list1 = ['Hello']
print(list1 * 4)
# ['Hello', 'Hello', 'Hello', 'Hello']
print(list1)
# ['Hello'] (original list remains unchanged)A repetition count of zero or a negative integer produces an empty list.
9.2.3 Membership
Membership operators check whether a particular element is present in a list.
inReturns True if the specified element is present; otherwise returns False.
not inReturns True if the specified element is absent; otherwise returns False.
list1 = ['Red', 'Green', 'Blue']
print('Green' in list1) # True
print('Cyan' in list1) # False
print('Cyan' not in list1) # True
print('Green' not in list1) # FalseFor ordinary strings in a list, matching is case-sensitive: 'red' in ['Red'] is False.
9.2.4 Slicing
Slicing extracts a portion of a list and returns it as a new list. The original list is not changed by a normal slice.
Syntax
list_name[start : stop]
list_name[start : stop : step]- start: index where extraction begins; included in the result.
- stop: index where extraction ends; excluded from the result.
- step: number of positions to move each time; default is 1.
Worked examples
list1 = ['Red', 'Green', 'Blue', 'Cyan',
'Magenta', 'Yellow', 'Black']
print(list1[2:6])
# ['Blue', 'Cyan', 'Magenta', 'Yellow']
print(list1[2:20])
# ['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']
# An oversized stop index is clipped to the list end.
print(list1[7:2])
# [] (start is beyond stop for a positive step)
print(list1[:5])
# ['Red', 'Green', 'Blue', 'Cyan', 'Magenta']
print(list1[0:6:2])
# ['Red', 'Blue', 'Magenta']
print(list1[-6:-2])
# ['Green', 'Blue', 'Cyan', 'Magenta']
print(list1[::2])
# ['Red', 'Blue', 'Magenta', 'Black']
print(list1[::-1])
# ['Black', 'Yellow', 'Magenta', 'Cyan', 'Blue', 'Green', 'Red']
Understanding a negative step
A negative step moves through the list from right to left. Therefore list1[::-1] returns the entire list in reverse order. The original list is still unchanged.
9.3 Traversing a List
Traversing means visiting or accessing every element of a list, usually to display, calculate or process its values. A list can be traversed using a for loop or a while loop.
(A) List traversal using a for loop
When the loop variable is used directly, it receives each element of the list one by one.
list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
for item in list1:
print(item)OutputRed
Green
Blue
Yellow
Black
Using range() and len()
Use this form when the index position is also needed.
list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
for i in range(len(list1)):
print(list1[i])(B) List traversal using a while loop
list1 = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
i = 0
while i < len(list1):
print(list1[i])
i += 1The index starts at 0 and increases by 1 after every iteration. The loop stops when i becomes equal to the list length.
| for loop | while loop |
|---|---|
| Directly visits each element. | Uses an index and a condition. |
| Convenient when every element must be processed. | Useful when the number of repetitions depends on a condition. |
Can use for item in list1 or for i in range(len(list1)). | Must initialise and update the index correctly. |
i += 1 in the while loop, the condition may remain True forever, causing an infinite loop.9.4 List Methods and Built-in Functions
Python provides list methods and built-in functions for adding, deleting, searching, sorting and calculating values. Methods are called using dot notation.
list_name.method_name(arguments)
Complete reference table (Tables 9.1 and continuation)
| Function / method | Purpose | Syntax / example | Important result |
|---|---|---|---|
len() | Returns the number of elements. | len(list1) | Returns an integer. |
list() | Creates an empty list if no argument is passed; converts an iterable/sequence into a list. | list()list('aeiou') | []['a','e','i','o','u'] |
append(x) | Adds one object at the end of the list. The object may itself be a list. | list1.append(50) | Changes the original list; returns None. |
extend(iterable) | Adds each element from an iterable to the end of the list. | list1.extend([40,50]) | Changes the original list; returns None. |
insert(i,x) | Inserts x at index i; later elements shift right. | list1.insert(2,25) | Changes the original list. |
count(x) | Counts how many times x occurs. | list1.count(10) | Returns a count; 0 if absent. |
index(x) | Returns the index of the first occurrence of x. | list1.index(20) | Raises ValueError if absent. |
remove(x) | Removes the first occurrence of the value x. | list1.remove(30) | Raises ValueError if absent. |
pop([i]) | Removes and returns the element at index i. If i is omitted, removes the last element. | list1.pop(3)list1.pop() | Returns the removed element; invalid index raises IndexError. |
reverse() | Reverses the elements in the same list. | list1.reverse() | In-place; returns None. |
sort() | Sorts the list in-place in ascending order by default. | list1.sort()list1.sort(reverse=True) | Changes original list; returns None. |
sorted() | Returns a new sorted list; original list remains unchanged. | list2 = sorted(list1) | Returns a new list. |
min() | Returns the smallest element. | min(list1) | Returns the minimum value. |
max() | Returns the largest element. | max(list1) | Returns the maximum value. |
sum() | Returns the sum of numeric elements. | sum(list1) | Returns a numeric total. |
1. len() and list()
list1 = [10, 20, 30, 40, 50]
print(len(list1)) # 5
empty_list = list()
print(empty_list) # []
str1 = 'aeiou'
list2 = list(str1)
print(list2) # ['a', 'e', 'i', 'o', 'u']
2. append() vs extend() – a very important difference
# append(): adds the complete object as one element
list1 = [10, 20, 30, 40]
list1.append([50, 60])
print(list1)
# [10, 20, 30, 40, [50, 60]]
# extend(): adds the elements individually
list2 = [10, 20, 30]
list2.extend([40, 50])
print(list2)
# [10, 20, 30, 40, 50]
append([50,60]) adds one nested-list element. extend([50,60]) adds two separate elements, 50 and 60.3. insert()
list1 = [10, 20, 30, 40, 50]
list1.insert(2, 25)
print(list1)
# [10, 20, 25, 30, 40, 50]
list1.insert(0, 5)
print(list1)
# [5, 10, 20, 25, 30, 40, 50]insert(index, value) inserts the value before the element currently at that index.
4. count() and index()
list1 = [10, 20, 30, 10, 40, 10]
print(list1.count(10)) # 3
print(list1.count(90)) # 0
list2 = [10, 20, 30, 20, 40, 10]
print(list2.index(20)) # 1 (first occurrence)
print(list2.index(90)) # ValueError: 90 is not in list
5. remove() and pop()
# remove(value): remove first matching value
list1 = [10, 20, 30, 40, 50, 30]
list1.remove(30)
print(list1)
# [10, 20, 40, 50, 30]
# pop(index): remove and return item at position
list2 = [10, 20, 30, 40, 50, 60]
removed = list2.pop(3)
print(removed) # 40
print(list2) # [10, 20, 30, 50, 60]
# pop() without index removes the last item
last_item = list2.pop()
print(last_item) # 60
6. reverse() and sort()
# reverse() changes order; it does not sort
list1 = [34, 66, 12, 89, 28, 99]
list1.reverse()
print(list1)
# [99, 28, 89, 12, 66, 34]
# sort() arranges values in ascending order
list2 = ['Tiger', 'Zebra', 'Lion', 'Cat', 'Elephant', 'Dog']
list2.sort()
print(list2)
# ['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']
# Descending order
list3 = [34, 66, 12, 89, 28, 99]
list3.sort(reverse=True)
print(list3)
# [99, 89, 66, 34, 28, 12]
7. sorted(), min(), max() and sum()
list1 = [23, 45, 11, 67, 85, 56]
list2 = sorted(list1)
print(list1) # [23, 45, 11, 67, 85, 56] (unchanged)
print(list2) # [11, 23, 45, 56, 67, 85]
numbers = [34, 12, 63, 39, 92, 44]
print(min(numbers)) # 12
print(max(numbers)) # 92
print(sum(numbers)) # 284
sort() changes the existing list and returns None. sorted() creates and returns a new sorted list, leaving the original unchanged. reverse() is not sorting: it only reverses the current order.9.5 Nested Lists
A nested list is a list that appears as an element inside another list. It is useful for representing tables, matrices, student records and grouped data.
Example 9.2
list1 = [1, 2, 'a', 'c', [6, 7, 8], 4, 9]
print(list1[4])
# [6, 7, 8]The fifth element (index 4) is itself a list. To access an element inside it, use two indices.
Syntax
list_name[outer_index][inner_index]list1 = [1, 2, 'a', 'c', [6, 7, 8], 4, 9]
print(list1[4][1])
# 7Here, list1[4] selects the inner list [6, 7, 8], and [1] selects its second element, 7.
Practical example: matrix
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
print(matrix[0][0]) # 10
print(matrix[1][2]) # 60
print(matrix[2][1]) # 809.6 Copying Lists
When copying a list, distinguish between creating an alias (another reference to the same list) and creating a separate copy (a different list object).
Assignment creates an alias, not a new list
list1 = [1, 2, 3]
list2 = list1
list1.append(10)
print(list1) # [1, 2, 3, 10]
print(list2) # [1, 2, 3, 10]list2 = list1 does not duplicate the list. Both variable names refer to the same object. Therefore, a change through either name is visible through the other name.
Three ways to create a separate (shallow) copy
Method 1: Slicing
oldList = [1, 2, 3, 4, 5]
newList = oldList[:]
print(newList) # [1, 2, 3, 4, 5]
Method 2: list() function
list1 = [10, 20, 30, 40]
list2 = list(list1)
print(list2) # [10, 20, 30, 40]
Method 3: copy() function from the copy module
import copy
list1 = [1, 2, 3, 4, 5]
list2 = copy.copy(list1)
print(list2) # [1, 2, 3, 4, 5]
copy.deepcopy(); the chapter's three methods demonstrate shallow copies.Comparison
| Operation | Creates a new outer list? | Effect of changing an outer element |
|---|---|---|
list2 = list1 | No | Visible through both names. |
list2 = list1[:] | Yes | Not reflected in the other outer list. |
list2 = list(list1) | Yes | Not reflected in the other outer list. |
list2 = copy.copy(list1) | Yes | Not reflected in the other outer list. |
9.7 List as Argument to a Function
When a list is passed to a function, Python passes a reference to the same list object. Two important situations must be understood.
(A) Modifying elements inside the function changes the original list
Program 9-1 increments every element of the list by 5.
def increment(list2):
for i in range(0, len(list2)):
list2[i] += 5
print('Reference of list Inside Function', id(list2))
list1 = [10, 20, 30, 40, 50]
print("Reference of list in Main", id(list1))
print("The list before the function call")
print(list1)
increment(list1)
print("The list after the function call")
print(list1)Output patternReference of list in Main: [same object ID]
The list before the function call
[10, 20, 30, 40, 50]
Reference of list Inside Function: [same object ID]
The list after the function call
[15, 25, 35, 45, 55]The ID printed inside the function is the same as the ID printed in the main program, because both references point to the same list. Therefore, changes to its elements are reflected in the calling code.
(B) Assigning a new list inside the function does not replace the caller's list
Program 9-2 assigns a new list to the local parameter name.
def increment(list2):
print("ID before assignment:", id(list2))
list2 = [15, 25, 35, 45, 55]
print("ID after assignment:", id(list2))
print("List inside the function:", list2)
list1 = [10, 20, 30, 40, 50]
print("ID before function call:", id(list1))
print("List before function call:", list1)
increment(list1)
print("ID after function call:", id(list1))
print("List after function call:", list1)Output patternList before function call: [10, 20, 30, 40, 50]
List inside the function: [15, 25, 35, 45, 55]
List after function call: [10, 20, 30, 40, 50]When list2 is assigned a new list, it becomes a local reference to a different object. The original list1 in the calling code remains unchanged.
9.8 List Manipulation
This section applies list methods to practical programming problems. The chapter includes a menu-driven list program and functions for calculating average marks and searching for a value.
Textbook Programs 9-1 to 9-5
Program 9-1: Increment list elements by 5
Concept: Passing a list to a function and modifying its elements in place.
def increment(list2):
for i in range(0, len(list2)):
list2[i] += 5
list1 = [10, 20, 30, 40, 50]
print("Before:", list1)
increment(list1)
print("After:", list1)OutputBefore: [10, 20, 30, 40, 50]
After: [15, 25, 35, 45, 55]Explanation: The loop visits every valid index. The statement list2[i] += 5 updates the element at that index. Since the function modifies the original list object, the caller sees the changes.
Program 9-2: Assign a new list inside a function
Concept: Reassigning the local parameter name does not alter the original list in the calling function.
def increment(list2):
list2 = [15, 25, 35, 45, 55]
print("List inside function:", list2)
list1 = [10, 20, 30, 40, 50]
print("Before function call:", list1)
increment(list1)
print("After function call:", list1)OutputBefore function call: [10, 20, 30, 40, 50]
List inside function: [15, 25, 35, 45, 55]
After function call: [10, 20, 30, 40, 50]Explanation: The assignment creates a new list and makes the local name list2 refer to it. The original list remains unchanged.
Program 9-3: Menu-driven list operations
Task: Build a menu that can append, insert, extend, modify, delete by position, delete by value, sort ascending, sort descending and display a list.
myList = [22, 4, 16, 38, 13]
while True:
print("\\nCurrent list:", myList)
print("\\nLIST OPERATIONS")
print("1. Append an element")
print("2. Insert an element at a position")
print("3. Append another list")
print("4. Modify an element")
print("5. Delete an element by position")
print("6. Delete an element by value")
print("7. Sort in ascending order")
print("8. Sort in descending order")
print("9. Display the list")
print("10. Exit")
choice = int(input("Enter your choice (1-10): "))
if choice == 1:
element = int(input("Enter element: "))
myList.append(element)
elif choice == 2:
element = int(input("Enter element: "))
pos = int(input("Enter index/position: "))
if 0 <= pos <= len(myList):
myList.insert(pos, element)
else:
print("Invalid position")
elif choice == 3:
newList = list(map(int, input(
"Enter elements separated by spaces: ").split()))
myList.extend(newList)
elif choice == 4:
pos = int(input("Enter index to modify: "))
if 0 <= pos < len(myList):
newElement = int(input("Enter new value: "))
oldElement = myList[pos]
myList[pos] = newElement
print("Modified", oldElement, "to", newElement)
else:
print("Invalid position")
elif choice == 5:
pos = int(input("Enter index to delete: "))
if 0 <= pos < len(myList):
removed = myList.pop(pos)
print("Deleted:", removed)
else:
print("Invalid position")
elif choice == 6:
element = int(input("Enter value to delete: "))
if element in myList:
myList.remove(element)
print("Deleted first occurrence of", element)
else:
print("Element not found")
elif choice == 7:
myList.sort()
print("List sorted in ascending order")
elif choice == 8:
myList.sort(reverse=True)
print("List sorted in descending order")
elif choice == 9:
print("The list is:", myList)
elif choice == 10:
print("Exiting program...")
break
else:
print("Invalid choice. Select 1 to 10.")eval(input(...)) to read a list. This teaching version uses split() and map(int, ...) instead, which is safer for user input. Positions in Python are zero-based indices.How the menu works
while Truerepeatedly displays the menu.input()reads the user's menu choice;int()converts it to an integer.- An if/elif chain selects the requested operation.
- List methods perform the required change.
- Choice 10 executes
breakand exits the loop. - An invalid choice displays an error message.
Program 9-4: Calculate average marks of n students
Task: Read the number of students, store each student's marks in a list and calculate the average using a user-defined function.
def computeAverage(list1, n):
total = 0
for marks in list1:
total = total + marks
average = total / n
return average
list1 = []
n = int(input("How many students' marks do you want to enter? "))
for i in range(0, n):
marks = int(input("Enter marks of student " + str(i + 1) + ": "))
list1.append(marks)
if n > 0:
average = computeAverage(list1, n)
print("Average marks of", n, "students is:", average)
else:
print("Number of students must be greater than zero.")Sample inputNumber of students: 5
Marks: 45, 89, 79, 76, 55OutputAverage marks of 5 students is: 68.8Explanation: The list stores marks. The function adds every mark to total, divides the total by n, and returns the average. The check for n > 0 prevents division by zero.
Program 9-5: Linear search in a list
Task: Search for a number in a list. If found, return its index; otherwise return None.
def linearSearch(num, list1):
for i in range(0, len(list1)):
if list1[i] == num:
return i
return None
list1 = []
maximum = int(input("How many numbers do you want to enter? "))
for i in range(0, maximum):
n = int(input("Enter number: "))
list1.append(n)
num = int(input("Enter number to search: "))
result = linearSearch(num, list1)
if result is None:
print("Number", num, "is not present in the list")
else:
print("Number", num, "is present at", result + 1, "position")Sample inputHow many numbers? 5
Numbers: 23, 567, 12, 89, 324
Number to search: 12OutputNumber 12 is present at 3 positionExplanation: Linear search checks elements from left to right. When a match is found, the function returns its zero-based index. The display adds 1 to show the human-friendly position. If the loop finishes without a match, the function returns None.
Chapter Summary
- Lists are mutable sequences in Python; their elements can be changed.
- List elements are enclosed in square brackets and separated by commas.
- A list inside another list is called a nested list.
- List indexing begins at 0; negative indexing accesses elements from the right.
- The
+operator concatenates lists and*repeats a list. inandnot intest whether an element is present.- Slicing extracts a part of a list.
- Lists can be traversed with for and while loops.
- Important list functions and methods include
len(),list(),append(),extend(),insert(),count(),index(),remove(),pop(),reverse(),sort(),sorted(),min(),max()andsum(). - Assignment can create an alias; slicing,
list()andcopy.copy()create separate shallow copies. - Modifying a list passed to a function can affect the original object; assigning a new list to the local parameter does not replace the caller's list.
Quick syntax reference
| Task | Syntax |
|---|---|
| Create a list | items = [10, 20, 30] |
| Empty list | items = [] or items = list() |
| Access element | items[0], items[-1] |
| Modify element | items[1] = 99 |
| Length | len(items) |
| Concatenate / repeat | a + b / a * 3 |
| Membership | 20 in items |
| Slicing | items[start:stop:step] |
| Traverse | for item in items: |
| Add one / many | items.append(x) / items.extend(other) |
| Insert / remove | items.insert(i,x) / items.remove(x) |
| Remove by index | items.pop(i) |
| Sort | items.sort() / sorted(items) |
| Copy | copy = items[:] |
| Nested element | matrix[row][column] |
Textbook Exercise – Worked Answers
1. Predict the output
(i) sort()
list1 = [12, 32, 65, 26, 80, 10]
list1.sort()
print(list1)Output:[10, 12, 26, 32, 65, 80]sort() sorts the original list in ascending order.
(ii) sorted()
list1 = [12, 32, 65, 26, 80, 10]
sorted(list1)
print(list1)Output:[12, 32, 65, 26, 80, 10]sorted(list1) returns a new sorted list, but the returned list is not stored. Therefore list1 remains unchanged.
(iii) Slicing and concatenation
list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]There is no printed output because neither expression is passed to print(). The expression results are:
list1[::-2]→[10, 8, 6, 4, 2].list1[:3] + list1[3:]→[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
(iv) Last element
list1 = [1,2,3,4,5]
list1[len(list1)-1]Expression result: 5. It is not displayed unless print() is used.
2. append() and extend()
myList = [10, 20, 30, 40]
myList.append([50, 60])After (i): [10, 20, 30, 40, [50, 60]]. The complete list [50, 60] is added as one element.
myList = [10, 20, 30, 40]
myList.extend([80, 90])After (ii), when considered independently: [10, 20, 30, 40, 80, 90]. Each item is added separately.
3. Print elements at even indices
myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0, len(myList)):
if i % 2 == 0:
print(myList[i])Output1
3
5
7
9Even indices are 0, 2, 4, 6 and 8. The values at those indices are odd numbers.
4. del statement and slices
(a) Delete from index 3 to the end
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)Output: [1, 2, 3]
(b) Delete the first five elements
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)Output: [6, 7, 8, 9, 10]
(c) Delete elements at even indices
myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)Output: [2, 4, 6, 8, 10]
5. Differentiate between append() and extend()
| append(x) | extend(iterable) |
|---|---|
| Adds its argument as one single element. | Adds each element of the iterable separately. |
a=[1,2]; a.append([3,4]) → [1,2,[3,4]] | a=[1,2]; a.extend([3,4]) → [1,2,3,4] |
| Argument may be any object. | Argument must be iterable. |
6. Difference between list1 * 2, list1 *= 2 and list1 = list1 * 2
list1 = [6, 7, 8, 9]
list1 * 2(a) Expression returns [6, 7, 8, 9, 6, 7, 8, 9], but does not change list1 unless assigned.
list1 = [6, 7, 8, 9]
list1 *= 2(b) Augmented assignment repeats the list and assigns the result back to list1. The variable now refers to a list containing the elements twice.
list1 = [6, 7, 8, 9]
list1 = list1 * 2(c) Creates the repeated list and reassigns the name list1 to it. The resulting values are the same as in (b). For ordinary lists, *= generally updates the list in place, while list1 = list1 * 2 binds the name to a newly created list.
7. Student record list
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8]- Percentage:
stRecord[3]→ 78.8. - Marks in fifth subject:
stRecord[2][4]→ 69. - Maximum marks:
max(stRecord[2])→ 99. - Roll number:
stRecord[1]→ 'A-36'. - Change name:
stRecord[0] = 'Raghav'.
stRecord[0] = 'Raghav'
print(stRecord)
# ['Raghav', 'A-36', [56, 98, 99, 72, 69], 78.8]Programming Problems – Model Solutions
Solutions below address all nine programming problems listed on printed pages 205–206. Each solution includes the core logic and handles common boundary cases.
1. Count the number of times an element occurs in a list
numbers = [10, 20, 10, 30, 10, 40]
target = int(input("Enter element to count: "))
frequency = numbers.count(target)
print(target, "occurs", frequency, "time(s)")Example: if target is 10, output is 10 occurs 3 time(s). The count() method counts occurrences.
2. Separate positive and negative integers into two lists
n = int(input("How many integers? "))
numbers = []
for i in range(n):
value = int(input("Enter integer: "))
numbers.append(value)
positive = []
negative = []
for value in numbers:
if value > 0:
positive.append(value)
elif value < 0:
negative.append(value)
print("Original list:", numbers)
print("Positive numbers:", positive)
print("Negative numbers:", negative)Zero is neither positive nor negative, so it remains only in the original list.
3. Function to return the largest element
def largest(numbers):
if len(numbers) == 0:
return None
maximum = numbers[0]
for value in numbers:
if value > maximum:
maximum = value
return maximum
data = [12, 45, 7, 89, 23]
print("Largest element:", largest(data))
# Largest element: 89The function assumes a non-empty list; the empty-list check returns None.
4. Function to return the second largest number
def secondLargest(numbers):
unique_values = sorted(set(numbers), reverse=True)
if len(unique_values) < 2:
return None
return unique_values[1]
data = [12, 45, 7, 89, 45, 23]
print("Second largest:", secondLargest(data))
# Second largest: 45This solution treats “second largest” as the second-largest distinct value. If fewer than two distinct values exist, it returns None.
5. Find the median of n integers
The median is the middle value after sorting. If the number of values is even, the median is the average of the two middle values.
n = int(input("How many integers? "))
numbers = []
for i in range(n):
numbers.append(int(input("Enter integer: ")))
if n == 0:
print("Median cannot be calculated for an empty list.")
else:
numbers.sort()
middle = n // 2
if n % 2 == 1:
median = numbers[middle]
else:
median = (numbers[middle - 1] + numbers[middle]) / 2
print("Sorted list:", numbers)
print("Median:", median)Example: [7, 2, 9, 4, 5] sorts to [2, 4, 5, 7, 9], so median = 5. For [2, 4, 6, 8], median = (4 + 6) / 2 = 5.
6. Remove duplicate elements from a list
items = [10, 20, 10, 30, 20, 40, 10]
unique_items = []
for item in items:
if item not in unique_items:
unique_items.append(item)
print("Original list:", items)
print("Without duplicates:", unique_items)
# [10, 20, 30, 40]This approach preserves the first-occurrence order of elements.
7. Insert an element at a user-specified position using a function
def insertElement(items, element, position):
if 0 <= position <= len(items):
items.insert(position, element)
return True
return False
numbers = [10, 20, 30, 40]
value = int(input("Enter element to insert: "))
position = int(input("Enter index/position (starting from 0): "))
if insertElement(numbers, value, position):
print("Updated list:", numbers)
else:
print("Invalid position")The valid insertion indices range from 0 through len(items), inclusive. Index 0 inserts at the beginning; index equal to the length inserts at the end.
8(a). Delete an element by its position using a function
def deleteByPosition(items, position):
if 0 <= position < len(items):
return items.pop(position)
return None
numbers = [10, 20, 30, 40, 50]
position = int(input("Enter index to delete (starting from 0): "))
removed = deleteByPosition(numbers, position)
if removed is None:
print("Invalid position")
else:
print("Deleted element:", removed)
print("Updated list:", numbers)
8(b). Delete an element by its value using a function
def deleteByValue(items, value):
if value in items:
items.remove(value)
return True
return False
numbers = [10, 20, 30, 20, 40]
value = int(input("Enter value to delete: "))
if deleteByValue(numbers, value):
print("Updated list:", numbers)
else:
print("Value not found")remove() deletes only the first occurrence of the value.
9. Reverse a list in-place without creating a new list
def reverseInPlace(items):
left = 0
right = len(items) - 1
while left < right:
items[left], items[right] = items[right], items[left]
left += 1
right -= 1
numbers = [10, 20, 30, 40, 50]
reverseInPlace(numbers)
print("Reversed list:", numbers)
# [50, 40, 30, 20, 10]Explanation: Two indices begin at opposite ends. Their elements are swapped, then the indices move towards the centre. The original list is modified directly; no second list is created.
Important Exam Points and Common Errors
- List indices start at 0. The last element is
items[len(items)-1]oritems[-1]. - Lists are mutable. Assignment to a valid index changes an element.
- Concatenation requires two lists; list plus string causes
TypeError. - In slicing, the stop index is excluded.
append()adds one object;extend()adds each item from an iterable.remove(value)deletes by value;pop(index)deletes by position and returns the deleted value.reverse()reverses current order;sort()arranges values in sorted order.sort()changes the original list;sorted()returns a new list.index()returns the first matching index and raisesValueErrorwhen the value is absent.list2 = list1creates an alias, not an independent copy.- A list passed to a function can be modified through the parameter. Reassigning the parameter to a new list does not replace the caller's variable.
- For a while-loop traversal, update the index. For an average, ensure the number of values is not zero.
TEXTBOOK SOLUTION
Step-by-step solved textbook exercises, derivations, and solutions.
Exercise Solutions Being Updated
Step-by-step verified exercise solutions are currently being uploaded.
IMPORTANT QUESTION
High-yield board questions, previous year questions (PYQs), and model answer keys.
Important Questions Being Compiled
Board blueprint and previous years' exam questions for this chapter will be live soon.