Skip to content

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 [].

fruits = ["Apple", "Banana", "Cherry"]
print(fruits[0]) # Output: Apple (Index starts at 0!)

3. Changeable (Mutable)ΒΆ

Unlike Strings, you can change a specific item in a list:

fruits[1] = "Mango" # Banana is now replaced! πŸ₯­


🎨 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 β†’