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 index0, not1. The last item is indexlen(arr) - 1(or simplyarr[-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
appendwhile reading input - Check
len(arr) > 0before usingarr[0]as a starting max/min range(len(arr))gives valid indexes:0throughlen(arr)-1
Common Mistakes
- Using index
1as 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.
Related Page
🔗Related Content
- 💻
Phase 4 - Practice Problems
Practice Phase 4 concepts with hands-on coding problems
- 📝
Phase 4 - Quiz
Test your Phase 4 understanding with assessment questions
- ➡️
Phase 5 - Get Started
Continue to Phase 5 after mastering Phase 4
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum