Lists — Basics & Operations
1136 words
6 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Lists — Basics & Operations > **Why read this?** You've stored single values (a number, a string). But what about a shopping list, student names, or daily temperatures?

Lists — Basics & Operations
Why read this? You've stored single values (a number, a string). But what about a shopping list, student names, or daily temperatures? Lists are Python's way of storing collections of related items in a single variable.
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Create lists with
[]and thelist()constructor - Access and modify elements using indexing
- Slice lists to extract subsequences
- Use list methods:
append,insert,remove,pop,sort,reverse - Understand list mutability vs. string immutability
📋 Prerequisites
- Strings — Basics & Operations — Indexing and slicing work similarly.
- For Loops & range() — Iterating lists.
📖 Core Content
14.1 What Problem Do Lists Solve?
Intuition: A variable holds one value. A list holds MANY values. Instead of
student1 = "Alice"; student2 = "Bob"; student3 = "Charlie", you write students = ["Alice", "Bob", "Charlie"] — one name, many items.14.2 Creating Lists
python# runnable empty = [] numbers = [1, 2, 3, 4, 5] mixed = [1, "hello", 3.14, True] nested = [1, 2], [3, 4], [5, 6](/courses/bscs1002/notes/1%2C%202%5D%2C%20%5B3%2C%204%5D%2C%20%5B5%2C%206) # list of lists print(empty) print(numbers) print(mixed) print(nested) # Using list() constructor chars = list("Python") print(chars) # ['P', 'y', 't', 'h', 'o', 'n'] # Range to list nums = list(range(5)) print(nums) # [0, 1, 2, 3, 4]
14.3 Indexing and Slicing (Same as Strings!)
python# runnable fruits = ["apple", "banana", "cherry", "date", "elderberry"] # Indexing print(fruits[0]) # apple (first) print(fruits[-1]) # elderberry (last) print(fruits[2]) # cherry # Slicing [start:stop:step] print(fruits[1:4]) # ['banana', 'cherry', 'date'] print(fruits[:3]) # ['apple', 'banana', 'cherry'] print(fruits[::2]) # ['apple', 'cherry', 'elderberry'] print(fruits[::-1]) # reversed list
14.4 Lists Are Mutable (Unlike Strings!)
python# runnable fruits = ["apple", "banana", "cherry"] print("Original:", fruits) # Modify an element fruits[1] = "blueberry" print("After change:", fruits) # ['apple', 'blueberry', 'cherry'] # Add elements fruits.append("date") print("After append:", fruits) # Insert at position fruits.insert(1, "apricot") print("After insert:", fruits) # Remove by value fruits.remove("apple") print("After remove:", fruits) # Remove by index (pop) last = fruits.pop() print(f"Popped: {last}, Remaining: {fruits}") first = fruits.pop(0) print(f"Popped first: {first}, Remaining: {fruits}") # Delete by index del fruits[0] print("After del:", fruits)
14.5 List Methods Reference
| Method | Description | Example | Result |
|---|---|---|---|
append(x) | Add x to end | [1].append(2) | [1, 2] |
insert(i, x) | Insert x at i | [1,3].insert(1,2) | [1, 2, 3] |
remove(x) | Remove first x | [1,2,3].remove(2) | [1, 3] |
pop(i) | Remove & return at i | [1,2,3].pop(1) | 2, list→[1,3] |
pop() | Remove & return last | [1,2,3].pop() | 3 |
index(x) | Find index of x | [1,2,3].index(2) | 1 |
count(x) | Count x in list | [1,2,2,3].count(2) | 2 |
sort() | Sort list in-place | [3,1,2].sort() | [1, 2, 3] |
reverse() | Reverse list in-place | [1,2,3].reverse() | [3, 2, 1] |
copy() | Shallow copy | a.copy() | New list |
14.6 Sorting Lists
python# runnable numbers = [3, 1, 4, 1, 5, 9, 2, 6] # In-place sort (modifies original) numbers.sort() print("In-place sort:", numbers) # sorted() returns new list (original unchanged) original = [3, 1, 4, 1, 5] sorted_list = sorted(original) print("Original:", original) print("Sorted:", sorted_list) # Descending numbers.sort(reverse=True) print("Descending:", numbers) # By key (e.g., length of string) words = ["python", "java", "c", "javascript", "go"] words.sort(key=len) print("By length:", words)
14.7 Iterating Over Lists
python# runnable fruits = ["apple", "banana", "cherry"] # Direct iteration for fruit in fruits: print(f"I like {fruit}") # With index for i in range(len(fruits)): print(f"{i}: {fruits[i]}") # enumerate() — best of both for i, fruit in enumerate(fruits): print(f"{i}: {fruit}")
14.8 Checking Membership
python# runnable fruits = ["apple", "banana", "cherry", "date"] print("banana" in fruits) # True print("grape" in fruits) # False print("grape" not in fruits) # True
14.9 List Operations
python# runnable # Concatenation a = [1, 2, 3] b = [4, 5, 6] c = a + b print("Concatenated:", c) # Repetition zeros = [0] * 5 print("Repeated:", zeros) # Length print("Length:", len(fruits)) # Min, Max, Sum (for numeric lists) nums = [10, 20, 30, 40, 50] print("Min:", min(nums)) print("Max:", max(nums)) print("Sum:", sum(nums)) print("Average:", sum(nums) / len(nums))
14.10 Worked Example 1: List Statistics
python# runnable numbers = [15, 22, 8, 31, 14, 27, 9, 3] total = sum(numbers) avg = total / len(numbers) max_val = max(numbers) min_val = min(numbers) print(f"Numbers: {numbers}") print(f"Sum: {total}") print(f"Average: {avg:.2f}") print(f"Max: {max_val}") print(f"Min: {min_val}") # Above average above = [n for n in numbers if n > avg] print(f"Above average: {above}")
14.11 Worked Example 2: Remove Duplicates
python# runnable items = ["apple", "banana", "apple", "cherry", "banana", "date"] unique = [] for item in items: if item not in unique: unique.append(item) print(f"Original: {items}") print(f"Unique: {unique}")
14.12 Worked Example 3: Matrix (2D List)
python# runnable matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Access element print(f"Element [1][2]: {matrix[1][2]}") # 6 # Print all elements for row in matrix: for val in row: print(val, end=" ") print()
14.13 Worked Example 4: List as Stack
python# runnable stack = [] # Push stack.append("Page 1") stack.append("Page 2") stack.append("Page 3") print("Stack:", stack) # Pop print("Pop:", stack.pop()) print("Stack:", stack) print("Pop:", stack.pop()) print("Stack:", stack)
📐 Key Concepts Reference
| Feature | Strings | Lists |
|---|---|---|
| Mutable? | No | Yes |
| Indexing | s[0] | lst[0] |
| Slicing | s[1:3] | lst[1:3] |
| Method modifies? | Returns new string | Often modifies in-place |
| Element types | Only characters | Any types, mixed |
len() | Yes | Yes |
in operator | Substring check | Membership check |
⚠️ Common Pitfalls
Pitfall 1: Modifying List While Iterating
The mistake: Removing items from a list while iterating over it causes skipped elements. Fix: Iterate over a copy:
for item in lst[:]:Pitfall 2: sort() vs sorted() Confusion
The mistake:
lst = lst.sort() — sort() returns None and modifies in-place, so lst becomes None. Fix: Use lst.sort() (in-place) or lst = sorted(lst) (new list).Pitfall 3: List Aliasing (Reference vs Copy)
The mistake:
b = a thinking you created a copy. Both variables point to the same list. Fix: Use b = a.copy() or b = a[:] for a shallow copy.📝 Practice Questions
Q1: What's the output?pythonlst = [1, 2, 3, 4, 5] print(lst[1:4])Answer:[2, 3, 4](indices 1, 2, 3) Q2: What's wrong with this code?pythonlst = [3, 1, 2] lst = lst.sort() print(lst)Answer:lst.sort()returnsNone. SolstbecomesNone. Fix:lst.sort()thenprint(lst). Q3: Write code to reverse a list without using reverse() or [::-1].Answer:pythonlst = [1, 2, 3, 4, 5] reversed_lst = [] for i in range(len(lst)-1, -1, -1): reversed_lst.append(lst[i]) print(reversed_lst)Q4-10: Additional list practice questions.(Following the same format with code answers in details blocks.)
🔗 Cross-References
- Next Topic: List Methods & Advanced Operations
- Previous Topic: Pattern Printing
- BSCS2002 PDSA: Lists are the foundation for arrays and dynamic data structures.
- Reference: Python for Everybody, Chapter 8 — "Lists"
- Video: L40: Warmup with lists, L57: More on lists Join Discord Previous13. Pattern PrintingNext15. List Operations