Arrays Part 1

In Task 15 (Charity Collection) you probably used three variables for the different amounts of money raised.
Run the following code to refresh your memory


In [ ]:
amount1=int(input("Please enter amount 1:"))
amount2=int(input("Please enter amount 2:"))
amount3=int(input("Please enter amount 3:"))

total = amount1 + amount2 + amount3
print("The total raised is", total)

In task 16 (Calculate the Area of a Rectangle Part 2) you probably used different variables for the two rectangles.
Run the following code to refresh your memory


In [ ]:
length1=int(input("Please enter length 1:"))
width1 =int(input("Please enter width  1:"))

length2=int(input("Please enter length 2:"))
width2 =int(input("Please enter width  2:"))

area1 = length1 * width1
area2 = length2 * width2

print("Area 1 is", area1)
print("Area 2 is", area2)

This is fine for programs that only need to process a small number of values, but becomes unwieldy with lots of values:

amount1=int(input("Please enter amount 1:"))
amount2=int(input("Please enter amount 2:"))
...
amount50=int(input("Please enter amount 50:"))

total = amount1 + amount2 + ... + amount50

If you had to write a program to accept 50 inputs like this, you would become quite frustrated. Surely there must be a better way?

Of course there is. We can now introduce the idea of arrays which can be used efficiently instead of lots of separate variables. (Arrays in the Python language are technically called lists).

Arrays

Instead of lots of separate variables, arrays can be used instead.
An array is a list of values:

names = ["Fred","Anna",...,"Mary"]      #an array of strings
tests = [45,34,...65]                   #an array of integers

Each vaue can be accessed by its index number, which always starts counting from 0:

index 0 1 ... 9
names "Fred" "Anna" ... "Mary"
tests 45 34 ... 65
names[0] #contains "Fred"
    names[1] #contains "Anna"

...etc.

Arrays can usually used with loops to display and process all the data:

for pupil in range(10):     #for each pupil from 0 to 9
        print(names[pupil])         #print the name of that pupil

    total = 0
    for pupil in range(10):             #for each pupil from 0 to 9
        total = total + tests[pupil]    #add that pupil’s mark to the total
    average = total / 10

Strings are actually arrays of characters:

name="fred" index 0 1 2 3
char f r e d

Variable Names

To avoid confusion when writing programs, use singular and plurals when you name variables:

variable name one or many? example
name a single name eg: name = "fred"
age a single age eg: age = 14
names an array of names eg: names[4] = "sue"
ages an array of lengths eg: ages[4] = 15

This makes is easier to remember whether a variable holds a single value or a list of values.

Arrays in Python

Please Run the following code. You can change the names, genders and marks if you want, but be very careful with all the quotes and brackes


In [29]:
# Working with Lists
# P Thoresen
# December 2013

names = ["Fred", "Sue", "Alan", "Mark", "Fiona", "Ian", "Edward", "Ruby", "Sean", "Sarah"]
genders = ["M", "F", "M", "M","F", "M", "M", "F", "M", "F"]
marks = [23, 54, 23, 76, 36, 35, 86, 25, 56, 87]
print(names, genders, marks, sep='\n')  #Just to show the arrays are set up properly


['Fred', 'Sue', 'Alan', 'Mark', 'Fiona', 'Ian', 'Edward', 'Ruby', 'Sean', 'Sarah']
['M', 'F', 'M', 'M', 'F', 'M', 'M', 'F', 'M', 'F']
[23, 54, 23, 76, 36, 35, 86, 25, 56, 87]

Next, run each of the following lines of code in turn and examine the output carefully.
You should be able to either predict or understand the output produced.


In [ ]:
print(names[0], marks[0])

In [ ]:
print(name[1],marks[1])

In [ ]:
print(len(names))

In [ ]:
for pupil in range(10):
    print(pupil)

In [ ]:
for pupil in range(len(names)):
    print(pupil)

In [ ]:
for pupil in range(10):
    print(names[pupil],marks[pupil], sep=': ')

In [ ]:
for pupil in range(10):
    if genders[pupil]=="M":
        print(names[pupil], "is a boy")
    else:
        print(names[pupil], "is a girl")

Exercise

5 empty cells are provided below. In each cell, write, and test, commands to:

  1. List each pupil’s name, gender and test mark:
  2. List the names and marks of each pupil, and if they have passed (50 marks or more) or failed:
  3. List the names and marks of all the boys who have passed:
  4. Count how many boys are in the class:
  5. Count how many boys scored 50 or more:

In [30]:
#List each pupil’s name, gender and test mark:

In [31]:
#List the names and marks of each pupil, and if they have passed (50 marks or more) or failed:

In [32]:
#List the names and marks of all the boys who have passed:

In [33]:
#Count how many boys are in the class:

In [35]:
#Count how many boys scored 50 or more:

Formatted Output (Tables)

Your programs from above should be displaying the correct results, but the output might be untidy:


In [36]:
for pupil in range(10):
    print(names[pupil],marks[pupil])


Fred 23
Sue 54
Alan 23
Mark 76
Fiona 36
Ian 35
Edward 86
Ruby 25
Sean 56
Sarah 87

These data can be displayed neatly using the format() function.
You have already used the format() function to display numbers to two decimal points.
The longest name is Edward – 6 characters. If all the names are printed out with 8 characters, and all the numbers with 2 characters, then the result will be a table with text left aligned and numbers right-aligned.


In [38]:
for pupil in range(10):
    nicename = format(names[pupil], '10') #format pupil name
    nicemark = format(marks[pupil], '2')  #format pupil mark
    print(nicename + nicemark)            #print formatted data


Fred      23
Sue       54
Alan      23
Mark      76
Fiona     36
Ian       35
Edward    86
Ruby      25
Sean      56
Sarah     87

Or more compactly:


In [41]:
for pupil in range(10):
    print(format(names[pupil], '10') + format(marks[pupil],'2'))


Fred      23
Sue       54
Alan      23
Mark      76
Fiona     36
Ian       35
Edward    86
Ruby      25
Sean      56
Sarah     87

You can now complete tasks 39 and 40.

Print this browser page in the usual way for your file.