Unit 2: Computational Thinking & Programming
Chapter 6: Lists in Python
1. Introduction to Lists
A List in Python is an ordered, mutable collection of heterogeneous items enclosed within square brackets [].
- Heterogeneous: Elements can be of different data types (integers, strings, floats, even other lists).
- Mutable: Elements can be added, updated, reordered, or deleted in-place without altering the list's identity.
empty_list = []
numbers = [10, 20, 30, 40]
mixed = [101, "Aarav", 94.5, True, [1, 2]] # Nested list
2. Accessing, Indexing, and Slicing Lists
Just like strings, lists support positive indexing (0 to n-1) and negative indexing (-1 down to -n).
lst = [10, 20, 30, 40, 50, 60]
print(lst[0]) # 10
print(lst[-1]) # 60
print(lst[1:4]) # [20, 30, 40]
print(lst[::-1]) # [60, 50, 40, 30, 20, 10]
In-Place Modification (Mutability)
grades = ['B', 'B', 'C']
grades[0] = 'A' # Valid! Lists are mutable
grades[1:3] = ['A+', 'A']
print(grades) # ['A', 'A+', 'A']
3. List Operators
- Concatenation (
+): Combines two lists into a single new list.[1, 2] + [3, 4]$\to$[1, 2, 3, 4] - Replication (
*): Duplicates list elements.[0] * 4$\to$[0, 0, 0, 0] - Membership (
in,not in):20 in [10, 20, 30]$\to$True
4. Built-in List Methods and Functions
| Method / Function | Description | Example Code | Resulting List |
|---|---|---|---|
len(L) |
Returns number of elements. | len([1, 2, 3]) |
3 |
L.append(x) |
Appends element x at the very end. |
a = [1, 2]; a.append(3) |
[1, 2, 3] |
L.extend(iter) |
Unpacks iterable and appends each element. | a = [1]; a.extend([2, 3]) |
[1, 2, 3] |
L.insert(i, x) |
Inserts item x at specified index i. |
a = [1, 3]; a.insert(1, 2) |
[1, 2, 3] |
L.pop([i]) |
Removes and returns item at index i (default: last). |
a = [10, 20]; a.pop() |
20 (a becomes [10]) |
L.remove(x) |
Removes first occurrence of value x. |
a = [1, 2, 1]; a.remove(1) |
[2, 1] |
L.clear() |
Removes all elements, leaving list empty. | a = [1, 2]; a.clear() |
[] |
L.count(x) |
Counts total occurrences of value x. |
[1, 2, 1, 1].count(1) |
3 |
L.index(x) |
Returns index of first occurrence of x. |
['a', 'b'].index('b') |
1 |
L.sort() |
Sorts items in ascending order in-place. | a = [3, 1, 2]; a.sort() |
[1, 2, 3] |
sorted(L) |
Returns a new sorted list (leaves original unchanged). | b = sorted([3, 1, 2]) |
[1, 2, 3] |
L.reverse() |
Reverses items in-place. | a = [1, 2, 3]; a.reverse() |
[3, 2, 1] |
Difference between
append()andextend(): -L.append([4, 5])appends the list itself as a single nested element:[1, 2, 3, [4, 5]](length + 1). -L.extend([4, 5])unpacks the items:[1, 2, 3, 4, 5](length + 2).
5. Copying Lists: Aliasing vs. Cloning
Assigning a list to a new variable creates an alias (reference pointer), not an independent copy:
# Aliasing (Modifying b modifies a!)
a = [1, 2, 3]
b = a
b.append(99)
print(a) # [1, 2, 3, 99] (Same object!)
# True Cloning / Shallow Copy
c = a.copy() # or c = a[:]
c.append(500)
print(a) # [1, 2, 3, 99] (Original is unharmed)
print(c) # [1, 2, 3, 99, 500]
6. Board Exam Practice Questions & Solutions
Q1. What will be the output of the following Python code?
list1 = [10, 20, 30, 40]
list2 = [50, 60]
list1.append(list2)
print("After append:", len(list1), list1)
list3 = [10, 20, 30, 40]
list3.extend(list2)
print("After extend:", len(list3), list3)
Answer:
After append: 5 [10, 20, 30, 40, [50, 60]]
After extend: 6 [10, 20, 30, 40, 50, 60]
Q2. Write a Python program to perform Linear Search on a list of integers. Answer:
def linear_search(arr, target):
for index, val in enumerate(arr):
if val == target:
return index
return -1
numbers = [24, 65, 12, 90, 43, 77]
key = int(input("Enter number to search: "))
pos = linear_search(numbers, key)
if pos != -1:
print(f"Element {key} found at index {pos}.")
else:
print(f"Element {key} not found in the list.")
Q3. Write a program to swap adjacent elements of a list of even length (e.g., [1, 2, 3, 4] becomes [2, 1, 4, 3]).
Answer:
lst = [10, 20, 30, 40, 50, 60]
for i in range(0, len(lst) - 1, 2):
lst[i], lst[i + 1] = lst[i + 1], lst[i]
print("Swapped List:", lst)
# Output: [20, 10, 40, 30, 60, 50]