Python Lists πΒΆ
Prerequisites: Python Variables, Python Loops
Mentor's Note: A list is like a multi-purpose container. It's the most flexible and commonly used way to store data in Python! π‘
π The Scenario: The Shopping Bag ποΈΒΆ
Imagine you are going to the market with a reusable shopping bag.
- The Logic:
- You can put many items inside (Apple, Milk, Bread). π¦
- The items are ordered (the Apple is at the bottom, the Bread is on top). π’
- You can change the items (swap the Milk for Juice). π
- You can have duplicates (you can buy two Apples). ππ
- The Result: A flexible collection of items that you can manage easily. β
π Concept ExplanationΒΆ
1. What is a List?ΒΆ
A list is a collection which is ordered and changeable. It allows duplicate members.
2. Creating & AccessingΒΆ
Lists are written with square brackets [].
3. Changeable (Mutable)ΒΆ
Unlike Strings, you can change a specific item in a list:
π¨ Visual Logic: List AnatomyΒΆ
graph LR
subgraph List: ["fruits"]
A[0: Apple] --- B[1: Banana]
B --- C[2: Cherry]
end
D[New Item] -- .append --> C
π» Implementation: The List LabΒΆ
# π Scenario: Managing a Task List
# π Action: Adding, removing, and sorting tasks
tasks = ["Code", "Eat", "Sleep"]
# 1. Add a new task β
tasks.append("Review")
# 2. Insert at a specific spot π
tasks.insert(1, "Fix Bug")
# 3. Remove the last completed task β
done = tasks.pop() # Removes "Review"
# 4. Sort alphabetically π‘
tasks.sort()
print(f"Remaining tasks: {tasks}")
# ποΈ Outcome: ["Code", "Eat", "Fix Bug", "Sleep"] (sorted)
π Sample Dry Run (Methods)ΒΆ
Initial List: L = [10, 20]
| Instruction | List State | Description |
|---|---|---|
L.append(30) |
[10, 20, 30] |
30 added to end π₯ |
L.pop(0) |
[20, 30] |
Item at index 0 (10) removed π€ |
L.extend([40, 50]) |
[20, 30, 40, 50] |
Multiple items added ποΈ |
π Complexity AnalysisΒΆ
- Accessing by Index: \(O(1)\) - Instant! β‘
- Adding to End (
append): \(O(1)\) - Very fast. - Inserting/Deleting at Start: \(O(n)\) - Slow (Python has to shift all other items).
π― Practice Lab π§ͺΒΆ
Task: The Guest List
Task: Create a list of 3 friends. Add a new friend to the beginning of the list using insert(). Then, print the total number of guests using len().
Hint: insert(0, "Name"). π‘
β Back: Control Flow | Next: Tuples β