CT Week 6: Lists & Strings

0. Prerequisites

NOTE

What you need to know:

  • Variables: Storing single values.
  • Loops: Iterating through items.

Quick Refresher

  • List: A collection of items in order. [10, 20, 30].
  • String: A sequence of characters. "Hello".
  • Index: The position of an item. Starts at 0.

1. Core Concepts

1.1 Indexing (0-Based)

  • First Item: Index 0.
  • Last Item: Index (where is length).
  • Access: L[0] gets the first item.

1.2 Operations

  1. Append: Add to end. L = L + [NewItem].
  2. Length: Count of items. Len(L).
  3. Slicing: Taking a part. L[Start : End].
    • Note: Usually includes Start, excludes End.

1.3 Strings as Lists

  • Strings behave like lists of characters.
  • S = "Cat". S[0] is “C”.
  • Concatenation: "Hello" + " " + "World" "Hello World".

2. Pattern Analysis & Goated Solutions

Pattern 1: The “Index” Trap (Off-by-One)

Context: “What is printed?” Code:

L = [10, 20, 30]
Print L[3]

TIP

Mental Algorithm:

  1. Number the Items:
    • 10 Index 0.
    • 20 Index 1.
    • 30 Index 2.
  2. Check Request: Request is Index 3.
  3. Result: Error! (Index Out of Bounds). Max index is 2.

Pattern 2: Filtering a List

Context: “Create a new list with only even numbers.” Code:

L = [1, 2, 3, 4]
NewL = []
For x in L:
    If x % 2 == 0:
        NewL = NewL + [x]

TIP

Mental Algorithm (Trace):

  1. Init: NewL = [].
  2. Loop 1 (x=1): Odd. Skip.
  3. Loop 2 (x=2): Even. Add 2. NewL = [2].
  4. Loop 3 (x=3): Odd. Skip.
  5. Loop 4 (x=4): Even. Add 4. NewL = [2, 4].

Pattern 3: String Traversal (Counting Vowels)

Context: “Count vowels in ‘Apple’.” Code:

S = "Apple"
Count = 0
For char in S:
    If char is Vowel:
        Count = Count + 1

TIP

Mental Algorithm:

  1. Iterate:
    • ‘A’ Vowel. Count=1.
    • ‘p’ No.
    • ‘p’ No.
    • ‘l’ No.
    • ‘e’ Vowel. Count=2. Answer: 2.

3. Practice Exercises

  1. Index: L=[5, 6, 7]. Value of L[1]?
    • Hint: 6.
  2. Length: Len("Hi")?
    • Hint: 2.
  3. Update: L=[1, 2]. L[0]=5. New L?
    • Hint: [5, 2].

🧠 Level Up: Advanced Practice

Question 1: List Indexing Trap

Problem: L = [10, 20, 30]. What is L[3]? Answer: Error. Indices are 0, 1, 2. Trap: 1-based thinking. Always remember 0-based indexing.

Question 2: String Slicing

Problem: S = "IIT Madras". Extract “Madras”. Logic:

  • I (0), I (1), T (2), (3), M (4)…
  • Start at index 4.
  • S[4 : ] (From 4 to end).

Question 3: Filtering a List

Problem: Create list B with only even numbers from A. Logic:

B = []
For x in A:
    If (x % 2 == 0):
        B = B ++ [x]  (Append)

Result: B contains even numbers in same order.