Python - Objective 08
Python - Objective 08
Python - Objective 08
TRY
Sample program:
# Arrays and Lists
# Main program
Sentence = ["The", "quick", "brown", "fox", "jumps"]
OutputList(Sentence)
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
Did you know that Python is widely reported as supporting only lists and not arrays. However, this isn’t true! A list in Python is an array,
it just behaves more like a list and therefore people mistakenly refer to the data structure as a list with Python. The “list” replicates the
functionality of both arrays and lists and therefore only one structure of this type is needed in Python.
We know this because Python keeps all elements of a list in contiguous memory and moves the entire data structure in memory when
it needs to without the programmer or user knowing. That’s an example of abstraction.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
# Main program
Sentence = ["The", "quick", "brown", "fox", "jumps"]
OutputList(Sentence)
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
TRY
Sample program:
# Arrays and Lists
# Main program
Sentence = ["The", "quick", "brown", "fox", "jumps"]
OutputList(Sentence)
Sentence[1] = "small"
Sentence[2] = "grey"
Sentence[3] = "squirrel"
OutputList(Sentence)
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE This program changes elements and outputs the contents of a list.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
TRY
Sample program:
# Arrays and Lists
# Main program
Sentence = []
for Counter in range(2):
Sentence.append("")
Sentence[0] = "Hello"
Sentence[1] = "World"
OutputList(Sentence)
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
# Main program • It is not necessary to put data into the list when it is created. You can declare an empty list, but it contains
Sentence = [] no indexes at this point.
for Counter in range(2): • You will need to initialise all the elements to something before it will have indexes.
Sentence.append("") • The for loop creates two elements and initialises them to an empty string.
• If Sentence contained numbers instead then you could use Sentence.append(0), but since Python adapts to
Sentence[0] = "Hello" different data structures automatically you don’t need to do this.
Sentence[1] = "World"
OutputList(Sentence)
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
TRY
Sample program:
# Arrays and Lists
# Main program
NewDatabase()
OutputProduct(1)
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE This program creates a 2D list, assigns data and outputs one row.
Understand how the code works: • Note this list has been declared outside of all the subroutines.
• This makes it a global data structure. That means all subroutines can use
# Arrays and Lists
global data without passing parameters.
• This program would be a little more efficient because it is not copying the
Product = [["" for X in range(2)] for Y in range(4)]
array when subroutines are called.
• The for loops initialise a list of a list with 4 rows and 2 columns.
# Subroutine to put data into the list
def NewDatabase():
global Product • You can create a table of data using a 2-dimension list.
Product[0][0] = "Cornflakes" ; Product[0][1] = "1.40" • A list can contain any number of dimensions.
Product[1][0] = "Weetabix" ; Product[1][1] = "1.20" • The semi colon allows you to put more than one command in a line of code.
Not generally recommended, but useful here.
# Subroutine to output a product from the list
def OutputProduct(Number):
global Product
print("{}: £{}".format(Product[Number][0], Product[Number][1])) • Data is added to the list. You can visualise it like this:
Product 0 1
# Main program 0 Cornflakes 1.40
NewDatabase() • The list is not passed to the subroutines
OutputProduct(1) because it is a global data structure in 1 Weetabix 1.20
this program. 2
• Note the use of the keyword global in
each subroutine. This is not actually 3
necessary in this program, but some
programs may not work if you don’t
include it.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
TRY
Sample program:
# Arrays and Lists
Pocket = []
# Main program
PutInPocket("Wallet")
PutInPocket("Keys")
PutInPocket("Tissue")
TakeOutOfPocket("Keys")
ShowPocket()
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
# Main program
PutInPocket("Wallet")
PutInPocket("Keys")
PutInPocket("Tissue")
TakeOutOfPocket("Keys")
ShowPocket()
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Learning points from this objective:
• An array is an identifier that holds more than one item of data of the same data type. In Python a list can contain data from different data types.
• Arrays are static data structures because the size of the array in memory cannot change when a program is executing.
• The item of data that an array or list holds is called an element.
• Each element is numbered with an index, starting with the first element at index 0.
• In python arrays and lists are the same type of data structure. You only need to understand the difference for exams.
• A list is a dynamic data structure because its size can change when the program is executing. That is because dynamic data structures are not held in contiguous
memory, each element contains a pointer to the next element in the structure that the programmer cannot see because it is abstracted. New elements can
easily be added and removed by changing the pointers. Lists are sometimes called linked lists too.
• The advantage of using an array or list instead of multiple variables is that you can use an iteration to loop through the elements it contains by using the index.
• If arrays or lists are given data that can never change in the program, like a constant, it is said to be immutable. If the data changes it is mutable.
• Enumeration is initialising data into an array or list when it is declared.
• Lists have many built-in methods that can be applied to them. A built-in method is just an algorithm that the programmer cannot see the code for.
• It may be easier to visualise an array and a list like this:
Array List
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Learning points from this objective:
• Arrays and lists are just an abstraction of memory. You can visualise 2D lists as either being [row, column] or [column, row], it doesn’t matter.
• Global data structures are available to all subroutines. They have a fixed memory footprint that does not change when the program is executing. That makes
them generally more CPU efficient (because data is not copied in memory), but less memory efficient (because the program doesn’t release the memory when
the data structure is not being used).
• Local data structures are only available to the subroutine they are declared in. Passing parameters is necessary to share local data between subroutines. That
makes them generally less CPU efficient, but more memory efficient.
• You should only use global data structures for data that is used very frequently by many subroutines. It is considered good practice to use local data structures
as much as possible. They allow the operating system to manage the memory better, reducing the need for virtual memory. They also create more isolated and
reusable program components.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Program comprehension: ITEM Identify a local data structure.
1. import random
2. Grid = [["" for X in range(5)] for Y in range(5)] Identify a global data structure.
3. def NewGrid():
4. random.seed()
5. for Y in range(5):
Identify a nested iteration.
6. for X in range(5):
7. ASCII = random.randint(1,26) + 64
8. Letter = chr(ASCII)
9. Grid[X][Y] = Letter
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Why does line 2 require two for loops, why can’t Grid simply be
Program comprehension: REASON
declared like this: Grid[[]] ?
1. import random
10.NewGrid()
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Keywords introduced in this objective:
X = ["e1", "e2"] Declares and enumerates a one-dimension list of strings.
Any data type can be used in the declaration with the correct qualifiers for the data inside the
squared brackets.
Lists can be passed into subroutines as paramters.
X = [] Declares an empty list.
Or… Data can be added to empty lists with the .append method, but a data cannot be added using
X = list() indexes until the elements are initialised.
X = ["" for Y in range(Z)] Initialises Z elements of list X.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
INVESTIGATE
Keywords introduced in this objective:
X.append(Y) Adds Y to list X.
X.sort() Sorts all the items in list X. Never use this as an answer to an exam question about sorting data in
a data structure. You need to show what the .sort method is doing to the data!
X.extend(Y) Appends list Y to list X.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
# Initialise data
Quote = [["" for X in range(2)] for Y in range(3)]
MAKE
RPG inventory problem:
1 point.
Write a program that will hold the inventory a player has in an RPG game. The player has the following actions: pick (adds an item to the
inventory), drop (removes an item from the inventory), pull (outputs a random item from the inventory) and search (outputs all the items
in the inventory).
Notebook problem:
1 point.
Write a program that allows the user to store up to 10 notes. The program should have this functionality on an infinite loop:
• Output all the notes stored, numbered 0-9.
• Ask the user to enter a number for a note to change.
• Ask the user to enter the new note.
• Over-write any existing note stored at that position.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
MAKE
Proc gen problem:
2 points.
Procedural generation is a popular technique in games design made famous by the 1984 game Elite, where planets in a galaxy and
creatures inhabiting those planets were generated using a deterministic algorithm.
Write a function that outputs a description of fictional animals that live on a planet. The function takes the number of the planet as an
integer parameter and uses this as a seed for a random number generator so that the same creatures always live on the same planet!
Data might include, but is not limited to:
Creatures: lizards, humanoids, insects
Colours: red, green, blue
Characteristics: shy, angry, docile
An example of an output for a planet might be: “Angry blue humanoids”.
It is important that the outcome is not truly random so that if planet 1652 contains angry blue humanoids, next time it is checked they are
still living there and haven’t been replaced by docile red lizards!
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
MAKE
Underground problem:
2 points.
Each line on the London underground has several stations. The Victoria line has these stations in the following order: Brixton, Stockwell,
Vauxhall, Pimlico, Victoria, Green Park, Oxford Circus, Warren Street, Euston, King's Cross, Highbury & Islington, Finsbury Park, Seven
Sisters, Tottenham Hale, Blackhorse Road and Walthamstow Central.
Write a program that allows the user to input two stations. A function should return the number of stops between the two stations. The
station names can be input in any order, but you can make the problem easier by only inputting stations in the correct order if you need to.
MAKE
Maths test problem:
3 points.
Write a program that generates a short test of the addition of two-digit numbers. The test contains five questions. The child taking the
test enters their name at the start of the test. The program stores the name of the child and their score out of five. It resets the test at the
end, ready for the next child who will see the same questions.
The names and scores are output before the next test starts.
Tanks problem:
3 points.
Tanks is a game for one player. At the start of the game, the computer places 10 tanks on an 8x8 board but does not reveal their
locations to the player. Each tank occupies one square on the board. The player enters a grid reference, e.g. 1,5 on each turn. The player
destroys the tank if the square is occupied by a tank. The player wins if they destroy all the tanks within 50 turns.
A visualisation of the tanks on the board for one player:
0 1 2 3 4 5 6 7
Write a program to play the game.
0
1 T T T
2 T T
3 T
4
5 T T
6
7 T T PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
MAKE
Strong numbers problem:
3 points.
A strong number is a number whose sum of the factorial of digits is equal to the original number.
E.g. 145 is strong number because 1! + 4! + 5! = 145.
That is: (1*1) + (4*3*2*1) + (5*4*3*2*1) = 145
Write a program that allows the user to enter an integer. The program outputs whether the number is strong or not and ensures that an
arithmetic overflow cannot crash the program.
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
EVALUATE
Test tables:
Problem: Underground
PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave
EVALUATE
Review your solutions:
Did you: Self-assess: Yes/No
Use a comment after each program branch to explain the purpose of the section?
Use a comment before each iteration to explain the purpose of the loop?
Test your programs against different types of data to check they work?
PYTHON T I M E