python-for-j277 / data-structures · Lesson 09
Lesson 09 — Data structures
1-D Arrays
Store a whole list of values under one name.
An array — called a list in Python — stores many values under a single name. A one-dimensional array is a simple line of items.
Making and reading an array
scores = [12, 8, 15, 9]
print(scores)
print(scores[0])
print(scores[2])Output
[12, 8, 15, 9] 12 15
How it works
- Square brackets create a list of values.
- Each item has a position number called an index.
- Indexing starts at 0, so
scores[0]is the first item andscores[2]is the third.
Changing and measuring an array
scores = [12, 8, 15, 9]
scores[1] = 20
print(scores)
print(len(scores))Output
[12, 20, 15, 9] 4
How it works
scores[1] = 20replaces the item at index 1.len()tells you how many items the list holds.
Adding items
shopping = ["bread", "milk"]
shopping.append("eggs")
print(shopping)Output
['bread', 'milk', 'eggs']
How it works
.append()adds a new item to the end of the list.- The list grows by one each time you append.
Looping through an array
scores = [12, 8, 15, 9]
total = 0
for score in scores:
total = total + score
print("Total:", total)
print("Average:", total / len(scores))Output
Total: 44 Average: 11.0
How it works
- A for-each loop visits every value in the list.
- We add each one to
total. - Dividing
totalbylen(scores)gives the average.
Mind the last indexValid indexes run from 0 to len − 1. A list of 4 items has indexes 0, 1, 2, 3. Asking for
scores[4] causes an error.One name, many valuesAn array stores many values under one name; reach any of them with an index in square brackets.
What you have learned
- A list (array) holds many values in square brackets.
- Index positions start at 0.
len()counts the items;.append()adds one to the end.- Change an item with
name[index] = value. - A for-each loop is the easy way to visit every item.