Imagine storing the marks of 40 students in 40 separate variables β m1, m2, m3β¦ π© That would be a nightmare! Python gives us a much smarter container: the list. π This chapter answers the BIG questions: How do we store many values under ONE name? How do we reach any item using its position? How do we add, change, remove and sort items? And how do we find the highest marks, the average, or search for a value in a list? Let's make a list! β
The most tested topics are indexing (positive and negative), slicing outputs, append() vs extend() vs insert(), pop() vs remove(), sort() vs sorted(), and programs on lists (max, min, average, search, count). For every slicing question, write the indexes above the items first β then it's easy!
6.1 π Introduction β What is a List?
A list is an ordered collection of items, written inside square brackets [ ] and separated by commas.
marks = [85, 92, 78, 64, 90]
fruits = ["apple", "mango", "banana"]
mixed = [101, "Riya", 92.5, True]
empty = []
print(marks)
print(mixed)
print(len(fruits))
Output:
[85, 92, 78, 64, 90]
[101, 'Riya', 92.5, True]
3
Analogy: A list is like a train π. The whole train has ONE name (
marks), and it has many coaches (items), each with a coach number (index). You can add coaches, remove them, or swap passengers!
Ordered
Items keep the order in which you put them
Position mattersMutable
You CAN change, add or remove items after creating the list
ChangeableMixed Types
One list can hold numbers, text and even other lists
Any typeDuplicates Allowed
The same value can appear many times
Repeats OK6.1.1 Other Ways to Create a List π οΈ
nums = list(range(1, 6)) # from range()
letters = list("HELLO") # from a string
print(nums)
print(letters)
Output:
[1, 2, 3, 4, 5]
['H', 'E', 'L', 'L', 'O']
Creating a list from user input:
marks = []
for i in range(3):
m = int(input("Enter marks: "))
marks.append(m)
print("Marks list:", marks)
Sample run (the user types 70, 85 and 60):
Enter marks: 70
Enter marks: 85
Enter marks: 60
Marks list: [70, 85, 60]
6.2 π’ Indexing β Reaching an Item
Every item has a position number called its index. Python gives two indexes to every item:
Items: "apple" "mango" "grape" "guava" "kiwi"
βββββββ βββββββ βββββββ βββββββ ββββββ
Positive: 0 1 2 3 4 β from the LEFT, starts at 0
Negative: -5 -4 -3 -2 -1 β from the RIGHT, starts at -1
fruits = ["apple", "mango", "grape", "guava", "kiwi"]
print(fruits[0])
print(fruits[3])
print(fruits[-1])
print(fruits[-2])
Output:
apple
guava
kiwi
guava
Front door starts at 0, back door starts at β1. The last item is ALWAYS list[-1], no matter how long the list is!
A list of 5 items has indexes 0 to 4. Writing fruits[5] gives IndexError: list index out of range.
6.2.1 Changing an Item βοΈ
Because lists are mutable, we can change an item using its index:
marks = [85, 92, 78]
marks[2] = 88
marks[-3] = 80
print(marks)
Output:
[80, 92, 88]
6.3 βοΈ Slicing β Taking a Part of the List
Slicing gives a new list containing a part of the original list.
list[start : stop : step]
- start β index to begin from (included). Default: beginning.
- stop β index to stop at (NOT included). Default: end.
- step β jump size. Default: 1.
L = [ 10, 20, 30, 40, 50, 60, 70 ]
index: 0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
L = [10, 20, 30, 40, 50, 60, 70]
print(L[1:4])
print(L[:3])
print(L[4:])
print(L[::2])
print(L[-3:])
print(L[::-1])
print(L[2:100])
Output:
[20, 30, 40]
[10, 20, 30]
[50, 60, 70]
[10, 30, 50, 70]
[50, 60, 70]
[70, 60, 50, 40, 30, 20, 10]
[30, 40, 50, 60, 70]
Analogy: Slicing is like cutting a piece of a cake π β
L[1:4]means "start cutting at piece 1, stop BEFORE piece 4". You get pieces 1, 2 and 3!
- The stop index is never included (just like
range()). - Slicing never gives an IndexError β
L[2:100]simply goes up to the end. L[::-1]gives the list reversed.- Slicing makes a new list β the original list is not changed.
"If L = [5, 10, 15, 20, 25, 30], write the output of L[1:5:2], L[-4:-1] and L[::-2]." β 3 marks
Answer: [10, 20], [15, 20, 25] and [30, 20, 10].
6.4 β List Operations
| Operation | Operator | Example | Result |
|---|---|---|---|
| Concatenation (joining) | + |
[1, 2] + [3, 4] |
[1, 2, 3, 4] |
| Repetition | * |
[0] * 4 |
[0, 0, 0, 0] |
| Membership | in, not in |
3 in [1, 2, 3] |
True |
| Comparison | ==, <, > |
[1, 2] == [1, 2] |
True |
a = [1, 2, 3]
b = [4, 5]
print(a + b)
print(b * 3)
print(2 in a, 9 not in a)
print([1, 2, 5] > [1, 2, 3])
Output:
[1, 2, 3, 4, 5]
[4, 5, 4, 5, 4, 5]
True True
True
+ a list with another list![1, 2] + 3 gives a TypeError. Write [1, 2] + [3] instead.
6.5 πΆ Traversing a List
Traversing means visiting each item one by one, usually with a for loop. There are two ways:
Way 1 β loop over the items directly:
colours = ["red", "green", "blue"]
for c in colours:
print(c.upper())
Output:
RED
GREEN
BLUE
Way 2 β loop over the indexes (when you need the position too):
colours = ["red", "green", "blue"]
for i in range(len(colours)):
print(i, colours[i])
Output:
0 red
1 green
2 blue
6.6 π§° List Functions and Methods
A function is written as function(list), and a method is written as list.method().
6.6.1 Adding Items β
graph TD
ADD["β ADDING ITEMS"]
AP["append(x)\nAdds ONE item\nat the END"]
EX["extend(list2)\nAdds EACH item of\nanother list at the END"]
IN["insert(i, x)\nAdds ONE item\nat index i"]
ADD --> AP
ADD --> EX
ADD --> IN
style AP fill:#4CAF50,color:#fff
style EX fill:#2196F3,color:#fff
style IN fill:#FF9800,color:#fff
L = [10, 20]
L.append(30)
print(L)
L.extend([40, 50])
print(L)
L.insert(1, 15)
print(L)
L.append([60, 70])
print(L)
print(len(L))
Output:
[10, 20, 30]
[10, 20, 30, 40, 50]
[10, 15, 20, 30, 40, 50]
[10, 15, 20, 30, 40, 50, [60, 70]]
7
L.append([60, 70]) adds the whole list as ONE item (a list inside a list).
L.extend([60, 70]) adds 60 and 70 as two separate items.
Analogy: You have a bag of 2 apples. π
- append(bag) β you put the whole bag inside your basket β 1 new thing.
- extend(bag) β you take out the apples and put them in one by one β 2 new things.
6.6.2 Removing Items β
| Method / Statement | What it does | Returns |
|---|---|---|
L.pop() |
Removes the last item | The removed item |
L.pop(i) |
Removes the item at index i | The removed item |
L.remove(x) |
Removes the first occurrence of value x | Nothing (None) |
del L[i] |
Deletes the item at index i (or a slice) | Nothing |
L.clear() |
Removes all items β list becomes [] |
Nothing |
L = [10, 20, 30, 20, 40, 50]
x = L.pop()
print(x, L)
y = L.pop(1)
print(y, L)
L.remove(20)
print(L)
del L[0]
print(L)
L.clear()
print(L)
Output:
50 [10, 20, 30, 20, 40]
20 [10, 30, 20, 40]
[10, 30, 40]
[30, 40]
[]
pop β position. remove β the real value. And only pop gives the item back to you!
[1, 2, 3].remove(9) gives ValueError: list.remove(x): x not in list. Check with if 9 in L: first.
6.6.3 Searching and Counting π
L = [5, 8, 5, 2, 5, 9]
print(L.count(5))
print(L.index(8))
print(L.index(5))
print(len(L))
Output:
3
1
0
6
count(x)β how many times x appears.index(x)β index of the first occurrence of x (ValueError if not found).
6.6.4 Sorting and Reversing π
L = [40, 10, 30, 20]
L.sort()
print(L)
L.sort(reverse=True)
print(L)
L.reverse()
print(L)
Output:
[10, 20, 30, 40]
[40, 30, 20, 10]
[10, 20, 30, 40]
sort() vs sorted():
marks = [70, 95, 60, 85]
new = sorted(marks)
print("sorted() :", new)
print("original :", marks)
marks.sort()
print("after sort():", marks)
Output:
sorted() : [60, 70, 85, 95]
original : [70, 95, 60, 85]
after sort(): [60, 70, 85, 95]
L.sort() |
sorted(L) |
|---|---|
| A method | A function |
| Changes the original list | Original list stays the same |
| Returns None | Returns a new sorted list |
L = L.sort()!sort() returns None, so L becomes None and your list is lost. Just write L.sort().
"Differentiate between sort() and sorted()." β 2 marks
Answer: sort() is a list method that sorts the list in place (changes the original list) and returns None. sorted() is a built-in function that returns a new sorted list and leaves the original list unchanged.
6.6.5 Built-in Functions for Numbers π
marks = [72, 88, 95, 61, 84]
print("Highest:", max(marks))
print("Lowest :", min(marks))
print("Total :", sum(marks))
print("Average:", sum(marks) / len(marks))
Output:
Highest: 95
Lowest : 61
Total : 400
Average: 80.0
All list functions and methods at a glance:
| Name | Type | Use |
|---|---|---|
len(L) |
Function | Number of items |
list(x) |
Function | Makes a list from a string, range, tuple⦠|
max(L) / min(L) |
Function | Largest / smallest item |
sum(L) |
Function | Total of all numbers |
sorted(L) |
Function | New sorted list |
append(x) |
Method | Add one item at the end |
extend(L2) |
Method | Add all items of L2 at the end |
insert(i, x) |
Method | Add x at index i |
pop(i) |
Method | Remove and return item at i (last if no i) |
remove(x) |
Method | Remove first occurrence of x |
clear() |
Method | Remove all items |
count(x) |
Method | How many times x appears |
index(x) |
Method | Index of first x |
sort() |
Method | Sort in place |
reverse() |
Method | Reverse in place |
6.7 π§© Nested Lists
A list can contain other lists as items. This is called a nested list β useful for storing tables of data.
students = [["Riya", 92], ["Aman", 85], ["Zoya", 78]]
print(students[1])
print(students[1][0])
print(students[2][1])
for s in students:
print(s[0], "scored", s[1])
Output:
['Aman', 85]
Aman
78
Riya scored 92
Aman scored 85
Zoya scored 78
students[1][0]
β β
β ββ item 0 inside that list β "Aman"
ββ item 1 of the outer list β ["Aman", 85]
Analogy: A nested list is like a cupboard with shelves ποΈ β
students[1]opens shelf 1, andstudents[1][0]picks the first thing on that shelf.
6.8 π» Important Programs on Lists
Code Example: max_without_function.py β Largest Item Without max()
L = [34, 78, 12, 95, 56]
largest = L[0]
for x in L:
if x > largest:
largest = x
print("Largest =", largest)
Output:
Largest = 95
Code Example: linear_search.py β Search for a Value
L = [15, 42, 8, 23, 42, 16]
key = int(input("Enter value to search: "))
found = False
for i in range(len(L)):
if L[i] == key:
print(key, "found at index", i)
found = True
break
if not found:
print(key, "not found")
Sample run (the user types 23):
Enter value to search: 23
23 found at index 3
Code Example: even_odd_count.py
L = [12, 7, 9, 20, 33, 18, 5]
even = 0
odd = 0
for x in L:
if x % 2 == 0:
even += 1
else:
odd += 1
print("Even:", even, "Odd:", odd)
Output:
Even: 3 Odd: 4
Code Example: above_average.py
marks = [45, 78, 62, 90, 55]
avg = sum(marks) / len(marks)
print("Average =", avg)
above = []
for m in marks:
if m > avg:
above.append(m)
print("Above average:", above)
Output:
Average = 66.0
Above average: [78, 90]
"Write a program to input a list of numbers and swap the elements at even positions with those at odd positions (0β1, 2β3 β¦)." β 3 marks Answer:
L = [1, 2, 3, 4, 5, 6]
for i in range(0, len(L) - 1, 2):
L[i], L[i + 1] = L[i + 1], L[i]
print(L)
Output: [2, 1, 4, 3, 6, 5]
β οΈ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
First item is L[1] |
Indexing starts at 0 | First item is L[0]; last is L[-1] |
L[len(L)] for the last item |
Index goes up to len β 1 | Use L[len(L) - 1] or L[-1] |
L[1:4] includes index 4 |
Stop is excluded | It gives indexes 1, 2, 3 |
L.append([4, 5]) adds two items |
append adds ONE item | Use L.extend([4, 5]) |
L.remove(2) removes index 2 |
remove works by value | Use L.pop(2) or del L[2] for index |
L = L.sort() |
sort() returns None | Write L.sort() alone |
sorted(L) changes L |
sorted() returns a new list | Use L.sort() to change L |
[1, 2] + 3 |
Can join only list with list | [1, 2] + [3] |
| "Lists are immutable like strings" | Lists can be changed | Lists are mutable |
L.insert(10) |
insert needs position AND value | L.insert(index, value) |
π Quick Revision β Exam Ready!
- List β ordered, mutable collection in
[ ]; items can be of any type; duplicates allowed - Create β
[ ],list("abc"),list(range(5)), orappend()in a loop - Indexing β positive from 0 (left), negative from β1 (right)
- Slicing β
L[start:stop:step]; stop excluded; no IndexError;L[::-1]reverses - Operations β
+join,*repeat,in/not in, comparisons - Traversing β
for x in Lorfor i in range(len(L)) - Add β
append(x)one item at end;extend(L2)many items;insert(i, x)at index i - Remove β
pop(i)by position (returns item);remove(x)by value;del L[i];clear() - Search β
count(x),index(x),x in L - Order β
sort()in place (returns None);sorted(L)new list;reverse();sort(reverse=True) - Numbers β
len(),max(),min(),sum(); average =sum(L) / len(L) - Nested list β
L[i][j]= item j of the list at position i
π― Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) If L = [3, 6, 9, 12], what is L[-2]?
Answer: 9
b) Which method adds an item at a given position?
Answer: insert()
c) What does [7] * 3 give?
Answer: [7, 7, 7]
d) Which method removes an item by its value?
Answer: remove()
e) What does L.sort() return?
Answer: None
Q2: Output Based [2 marks]
L = [10, 20, 30, 40, 50, 60]
print(L[2:5])
print(L[::-2])
print(L[-5:-2])
print(L[:2] + L[4:])
Answer:
[30, 40, 50]
[60, 40, 20]
[20, 30, 40]
[10, 20, 50, 60]
Q3: Output Based [3 marks]
L = [4, 7, 1]
L.append(9)
L.insert(0, 5)
L.extend([2, 7])
print(L)
L.remove(7)
print(L.pop(2), L)
print(L.count(7), L.index(9))
Answer:
[5, 4, 7, 1, 9, 2, 7]
1 [5, 4, 9, 2, 7]
1 2
Q4: Short Answer [2 marks]
Differentiate between append() and extend() with an example.
Answer: append() adds its argument as a single item at the end, while extend() adds each item of the given list at the end.
A = [1, 2]
A.append([3, 4])
print(A)
B = [1, 2]
B.extend([3, 4])
print(B)
Output:
[1, 2, [3, 4]]
[1, 2, 3, 4]
Q5: Program [3 marks]
Write a program to input 5 numbers into a list and print the list, the largest number and the average.
Answer:
L = []
for i in range(5):
L.append(int(input("Enter number: ")))
print("List:", L)
print("Largest:", max(L))
print("Average:", sum(L) / len(L))
Sample run (the user types 4, 9, 2, 7 and 3):
Enter number: 4
Enter number: 9
Enter number: 2
Enter number: 7
Enter number: 3
List: [4, 9, 2, 7, 3]
Largest: 9
Average: 5.0
βοΈ Practice Problems
- Create a list of your 5 favourite foods and print the first, the last and the middle item.
- If
L = ['P', 'Y', 'T', 'H', 'O', 'N'], write the output ofL[1:4],L[-3:],L[::3]andL[::-1]. - Write the output:
print([1, 2] * 2 + [3]) - What is the difference between
pop()andremove()? Give an example of each. - Write a program to count how many times a number entered by the user appears in a list.
- Write a program to find the smallest number in a list without using
min(). - Write a program to create a new list containing only the even numbers of a given list.
- Write a program to input 5 names into a list, sort them in alphabetical order and print them.
- Write a program to replace every negative number in a list with 0.
- Write a program to remove all the duplicates from a list (e.g.
[1, 2, 2, 3, 1]β[1, 2, 3]). - For
S = [["Asha", 88], ["Ravi", 76]], what isS[1][1]? Write a loop to print each name with its marks. - Write a program to input a list of marks and print how many students scored above 75.