UNIHIVE

Study Hub UNIPORT MTH 280

MTH 280 · Introduction to Computer programming

Arrays and lists

Storing many values under one name, indexing, reading and processing arrays with loops, searching, sorting and two-dimensional arrays.

Our notes

2 min read

What an array is

An array stores many values of the same kind under one name; each is reached by its index (position). In Python the built-in list does this job.
scores = [55, 72, 40, 68, 81]

  • Python indexes from 0: scores[0] is 55, scores[4] is 81. (FORTRAN starts at 1 by default.)
  • len(scores) is 5. scores[-1] is the last item, 81.
  • Change an item: scores[2] = 45.
  • Add an item: scores.append(90).

Processing an array with a loop

Total and average:
total = 0
for s in scores:
    total = total + s
average = total / len(scores)
With [55, 72, 40, 68, 81]: total = 316, average = 63.2.

Largest value and its position:
big = scores[0]
pos = 0
for i in range(1, len(scores)):
    if scores[i] > big:
        big = scores[i]
        pos = i
Result: big = 81, pos = 4.

Reading N values into an array:
n = int(input())
a = []
for i in range(n):
    a.append(float(input()))

Searching

  • Linear search: check each item in turn until found (works on any list; up to n comparisons).
  • Binary search: on a sorted list, compare with the middle item and throw away half each time (about log₂ n comparisons: 1,000 items need at most 10).

Worked example (binary search for 23 in [3, 8, 15, 23, 42, 57, 61]). Middle (index 3) is 23 → found in 1 comparison. For 57: middle 23 < 57 → search [42, 57, 61]; middle 57 → found in 2 comparisons.

Sorting: bubble sort

Compare neighbours and swap them if out of order; after each pass the largest remaining value "bubbles" to the end.
for i in range(n - 1):
    for j in range(n - 1 - i):
        if a[j] > a[j + 1]:
            a[j], a[j + 1] = a[j + 1], a[j]
Trace [5, 1, 4, 2]: pass 1 → [1, 4, 2, 5]; pass 2 → [1, 2, 4, 5]; pass 3 → no swaps. Sorted: [1, 2, 4, 5].

Two-dimensional arrays (matrices)

A table of rows and columns, e.g. three students' scores in two courses:
marks = [[60, 70], [45, 50], [80, 75]]
marks[2][0] is 80 (row 2, column 0). Use a nested loop to visit every cell. Adding two matrices: c[i][j] = a[i][j] + b[i][j].

Exams usually ask: declare and fill an array; sum, average, largest and smallest; count values above a mark; linear vs binary search; trace a bubble sort; matrix addition with nested loops.

Common mistake: going one past the end (an "index out of range" error): a list of 5 items has indexes 0 to 4, not 1 to 5.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All MTH 280 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.