Block 7: Lists & Basic Operations
Create and manipulate Python lists for storing sequences of data.
Concepts
- List creation, indexing (positive and negative)
- Slicing: list[start:stop:step]
- append(), remove(), pop(), insert()
- len(), sum(), min(), max()
Code Examples
Indexing and slicing
nums = [10, 20, 30, 40, 50]
print(nums[0], nums[-1])
print(nums[1:4])
print(nums[::2])
List methods
lst = [1, 2, 3]
lst.append(4)
lst.insert(0, 0)
print(lst)
x = lst.pop()
print(x, lst)
Exercise
Store daily step counts for 7 days. Compute total and average. Given a list of marks, remove the lowest mark and compute the new average.
Solution
steps = [5000, 7200, 4500, 8000, 6000, 5500, 9000]
total = sum(steps)
avg = total / len(steps)
print(f'Total: {total}, Average: {avg:.0f}')
marks = [85, 72, 90, 68, 88]
marks.remove(min(marks))
new_avg = sum(marks) / len(marks)
print(f'New average (lowest removed): {new_avg:.1f}')Practice Problems
Problem 1: Reverse a list using slicing (without reverse())
Hint: lst[::-1]
Problem 2: Get every second element from a list starting at index 0
Hint: lst[::2]
Application
Lists store sequences: time series data, feature vectors, batches of samples. Slicing extracts subsets for analysis.
Case Study
A sensor records temperatures every hour. The last 24 values are kept in a list. Slicing [-24:] gets yesterday's data.
Homework
What is the difference between list.append(x) and list.insert(0, x)? Give examples.