MASTER YOUR LOGIC BUILDING:Phase 6 - Category 3: Array Logic

Mastering phase 6 - category 3: array logic concepts and implementation.

Array Logic

Why This Matters

Lists (arrays) hold collections — test scores, prices, temperatures. Real array problems often need more than one pass: first find the maximum, then find everything above average; first separate zeros, then rebuild the list. This chapter teaches you to plan multi-step list operations without losing your place.

What You'll Learn

  • How to validate whether a list is sorted
  • How to find second largest / second smallest elements
  • How to rearrange elements (shift zeros, filter by condition)
  • When to use one pass vs two passes through a list

Think in Passes

Many array problems naturally split into stages:

One pass — do everything in a single loop (count, sum, find max)

Two passes — first loop gathers info (find max), second loop uses it (find largest value that isn't max)

arr = [10, 5, 20, 15, 20]

# Pass 1: find maximum
max_val = arr[0]
for num in arr:
    if num > max_val:
        max_val = num

# Pass 2: find second largest (biggest number that isn't max)
second_max = None
for num in arr:
    if num != max_val:
        if second_max is None or num > second_max:
            second_max = num

print(second_max)   # 15

Step-by-Step: Shift Zeros to the End

Given [1, 0, 2, 0, 3, 4] → want [1, 2, 3, 4, 0, 0]

  1. Create two empty lists: one for non-zeros, one for zeros
  2. Loop through the array — sort each element into the right bucket
  3. Combine: non-zeros first, then zeros
arr = [1, 0, 2, 0, 3, 4]
non_zeros = []
zeros = []

for element in arr:
    if element == 0:
        zeros.append(0)
    else:
        non_zeros.append(element)

result = non_zeros + zeros
print(result)   # [1, 2, 3, 4, 0, 0]

This preserves the original order of non-zero elements — important!

Check If a List Is Sorted

Walk through and verify each element is ≤ the next:

arr = [1, 2, 3, 5, 4]
is_sorted = True

for i in range(len(arr) - 1):
    if arr[i] > arr[i + 1]:
        is_sorted = False
        break

print(is_sorted)   # False (4 comes after 5)

Elements Above Average

arr = [10, 20, 30, 40]
total = sum(arr)
average = total / len(arr)

above_avg = [x for x in arr if x > average]
print(above_avg)   # [30, 40]

Two steps: compute average, then filter. Simple and readable.

Common Mistakes & Tips

  • Second largest when all elements are equal — handle the "no second max exists" case
  • Off-by-one in loop range — checking sorted uses range(len(arr) - 1), not len(arr)
  • Losing original order — when shifting zeros, don't just sort; that changes non-zero order too
  • Empty or single-element lists — always ask: "What if the list has 0 or 1 items?"
  • Tip: Write down a tiny example array and trace each pass by hand before coding

Practice Focus

  • Shift all zeros to the end while keeping other elements in order
  • Find the second largest element in a list
  • Check if a list is sorted in ascending order
  • Count elements greater than the average
  • Remove the minimum and maximum, then print the sum of what's left

Array logic is about having a clear plan before you loop. Decide your passes first, then code!

Hands-on Examples

Shift Zeros to End

# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
    arr.append(int(input(f"Enter element {i+1}: ")))

# Shift zeros to end
non_zeros = []
zeros = []

for element in arr:
    if element == 0:
        zeros.append(0)
    else:
        non_zeros.append(element)

# Combine
result = non_zeros + zeros
print(f"Array with zeros at end: {result}")

Separate array into non-zero and zero elements. Combine non-zeros first, then zeros. This preserves order of non-zero elements.