Lesson 12 of 19 · 7 min
Lists — Ordered, Mutable Collections
WHY Lists?
Without lists: s1=85; s2=92; s3=78; s4=65 — four separate variables for four scores. With 100 students, you need 100 variables. A list holds all of them in one variable, and a single for loop processes every score.
Creating Lists
fruits = ["apple", "banana", "mango", "grape"] # list of strings
scores = [85, 92, 78, 65, 88] # list of integers
mixed = ["Ahmed", 21, True, 3.75] # mixed types — valid but unusual
empty = [] # empty list to fill later
chars = list("Python") # string → list of individual characters
print(chars) # ['P', 'y', 't', 'h', 'o', 'n']
Output: ['P', 'y', 't', 'h', 'o', 'n']
Indexing — Zero-Based
fruits = ["apple", "banana", "mango", "grape", "kiwi"] # [0] [1] [2] [3] [4] ← positive indexes # [-5] [-4] [-3] [-2] [-1] ← negative indexes print(fruits[0]) # apple — first item (0, not 1!) print(fruits[2]) # mango — third item print(fruits[-1]) # kiwi — last item using negative index print(fruits[-2]) # grape — second-to-last
Output: apple mango kiwi grape
Slicing — [start : stop : step]
stop index is not included. Think of it as "up to but not including".
fruits = ["apple", "banana", "mango", "grape", "kiwi"] print(fruits[1:4]) # ['banana', 'mango', 'grape'] — index 1 up to (not incl.) 4 print(fruits[:3]) # ['apple', 'banana', 'mango'] — from start up to index 3 print(fruits[2:]) # ['mango', 'grape', 'kiwi'] — index 2 to the end print(fruits[::2]) # ['apple', 'mango', 'kiwi'] — every 2nd item (step=2) print(fruits[::-1]) # ['kiwi', 'grape', 'mango', 'banana', 'apple'] — reversed
Output: ['banana', 'mango', 'grape'] ['apple', 'banana', 'mango'] ['mango', 'grape', 'kiwi'] ['apple', 'mango', 'kiwi'] ['kiwi', 'grape', 'mango', 'banana', 'apple']
Adding Items
fruits = ["apple", "banana"]
fruits.append("mango") # add ONE item to the END
print(fruits) # ['apple', 'banana', 'mango']
fruits.insert(1, "grape") # insert at index 1 — push existing items right
print(fruits) # ['apple', 'grape', 'banana', 'mango']
fruits.extend(["kiwi", "pear"]) # add ALL items from another iterable to the end
print(fruits) # ['apple', 'grape', 'banana', 'mango', 'kiwi', 'pear']
Output: ['apple', 'banana', 'mango'] ['apple', 'grape', 'banana', 'mango'] ['apple', 'grape', 'banana', 'mango', 'kiwi', 'pear']
Removing Items
fruits = ["apple", "banana", "mango", "grape", "banana"]
fruits.remove("banana") # removes FIRST occurrence only (not all)
print(fruits) # ['apple', 'mango', 'grape', 'banana']
last = fruits.pop() # removes AND RETURNS the last item
print(f"Popped: {last}") # Popped: banana
print(fruits) # ['apple', 'mango', 'grape']
item = fruits.pop(1) # removes AND RETURNS item at index 1
print(f"Popped: {item}") # Popped: mango
print(fruits) # ['apple', 'grape']
fruits.clear() # removes ALL items — list is now empty
print(fruits) # []
Output: ['apple', 'mango', 'grape', 'banana'] Popped: banana ['apple', 'mango', 'grape'] Popped: mango ['apple', 'grape'] []
Sorting
nums = [3, 1, 4, 1, 5, 9, 2, 6] nums.sort() # sort ASCENDING in-place (modifies original list) print(nums) # [1, 1, 2, 3, 4, 5, 6, 9] nums.sort(reverse=True) # sort DESCENDING in-place print(nums) # [9, 6, 5, 4, 3, 2, 1, 1] words = ["banana", "apple", "cherry"] new = sorted(words) # sorted() returns a NEW list — original is UNCHANGED print(new) # ['apple', 'banana', 'cherry'] print(words) # ['banana', 'apple', 'cherry'] — still original order! nums.reverse() # reverse the current order in-place (not sort — just flip) print(nums) # [1, 1, 2, 3, 4, 5, 6, 9]
Output: [1, 1, 2, 3, 4, 5, 6, 9] [9, 6, 5, 4, 3, 2, 1, 1] ['apple', 'banana', 'cherry'] ['banana', 'apple', 'cherry'] [1, 1, 2, 3, 4, 5, 6, 9]
Other Useful List Methods
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5] print(len(nums)) # 9 — total number of items print(nums.count(1)) # 2 — how many times 1 appears print(nums.index(5)) # 4 — index of the FIRST occurrence of 5 print(5 in nums) # True — fast membership check with 'in' print(10 in nums) # False copy = nums.copy() # create an INDEPENDENT copy nums.clear() # empty the original print(copy) # [3, 1, 4, 1, 5, 9, 2, 6, 5] — copy is intact print(nums) # [] — original is now empty
Output: 9 2 4 True False [3, 1, 4, 1, 5, 9, 2, 6, 5] []
List Methods Quick Reference Table
| Method | What It Does | Example |
|---|---|---|
.append(x) | Add x to end | lst.append(5) |
.insert(i, x) | Insert x at index i | lst.insert(0, "first") |
.remove(x) | Remove first occurrence of x | lst.remove("apple") |
.pop() | Remove & return last item | item = lst.pop() |
.pop(i) | Remove & return item at index i | item = lst.pop(2) |
.sort() | Sort ascending in-place | lst.sort() |
.sort(reverse=True) | Sort descending in-place | lst.sort(reverse=True) |
.reverse() | Reverse in-place | lst.reverse() |
.extend(lst2) | Add all items from lst2 to end | lst.extend([4, 5]) |
.count(x) | Count occurrences of x | lst.count("apple") |
.index(x) | First index of x | lst.index("banana") |
.clear() | Remove all items | lst.clear() |
.copy() | Return independent copy | new = lst.copy() |
sorted(lst) | Return NEW sorted list | new = sorted(lst) |
List Comprehension — Compact List Creation
Pattern: [expression for item in iterable if condition]
# Traditional way — verbose
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension — same result, one clean line
squares = [i ** 2 for i in range(1, 6)] # square each number from 1 to 5
print(squares) # [1, 4, 9, 16, 25]
# With a filter condition — only keep even numbers
evens = [i for i in range(1, 21) if i % 2 == 0]
print(evens) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Transform strings
words = ["hello", "world", "python"]
upper = [w.upper() for w in words] # convert each word to uppercase
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
# Conditional expression — transform based on condition (not filter)
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']
Output: [1, 4, 9, 16, 25] [1, 4, 9, 16, 25] [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] ['HELLO', 'WORLD', 'PYTHON'] ['even', 'odd', 'even', 'odd', 'even']
