Python Lists ๐¶
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 โ