MASTER YOUR LOGIC BUILDING:Phase 4 - Level 1: Basic Arrays

Mastering phase 4 - level 1: basic arrays concepts and implementation.

Phase 4 - Level 1: Basic Arrays

Why This Matters

So far you've mostly worked with one value at a time. Real programs deal with many values: marks of a class, prices in a cart, names in a contact list. An array (called a list in Python) is a single variable that holds a row of values — like a row of lockers, each with a number on the door.

What You'll Learn

  • How to create lists and read/write values by index
  • Why indexing starts at 0
  • How to loop through every element
  • The accumulator pattern (sum, max, count)

Creating and Accessing Lists

arr = [10, 20, 30, 40, 50]
print(arr[0])   # 10 — first locker
print(arr[2])   # 30 — third locker (index 2)
print(arr[-1])  # 50 — last locker
print(len(arr)) # 5 — how many lockers
Remember: The first item is index 0, not 1. The last item is index len(arr) - 1 (or simply arr[-1]).

Growing a list

scores = []
scores.append(85)
scores.append(90)
scores.append(78)
# scores is now [85, 90, 78]

Walking Through Every Element

Two common ways:

# By value — "give me each number"
for num in arr:
    print(num)

# By index — "I need the position too"
for i in range(len(arr)):
    print(i, arr[i])

The Accumulator Pattern (Very Important)

To find a sum, max, or count, you keep a running answer and update it as you walk:

total = 0
for num in arr:
    total = total + num
print(total)

How to think: Start with 0. Visit each locker. Add what's inside. At the end, total is the sum.

Same idea for maximum:

maximum = arr[0]
for num in arr:
    if num > maximum:
        maximum = num

Tips

  • Empty list first, then append while reading input
  • Check len(arr) > 0 before using arr[0] as a starting max/min
  • range(len(arr)) gives valid indexes: 0 through len(arr)-1

Common Mistakes

  • Using index 1 as the first element
  • Using arr[len(arr)] — that's one past the end (IndexError)
  • Forgetting to initialize the accumulator before the loop

Practice Focus

In the examples below, practice reading a list from input, printing it, summing it, and finding max/min. Get comfortable with indexes before moving to searching and transforming.

Hands-on Examples

Input and Print Array

# Take n as input
n = int(input("Enter number of elements: "))

# Input array
arr = []
print("Enter elements:")
for i in range(n):
    element = int(input())
    arr.append(element)

# Print array
print("Array elements:")
for element in arr:
    print(element, end=" ")
print()

Use a loop to input n elements and append to list. Then iterate through list to print all elements.