Skip to content

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

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 โ†’