More 1-D Arrays

At National 5 it is important to not only be able to read from and use the data within an array, but also adding data into the array.

How this is different

So far, the 1-D arrays that have been used look like this. They have data in them and that data can be accessed

names = ["John", "Mary", "Betty", "David", "Sam"]

print(names[0]) # Prints John

However, at National 5, its common that the array starts with no data. This data needs to be added to the array using code.

Creating the array

When creating arrays with no values, you will need to work out the data type, how many items the array needs to hold.

Arrays will then be by stating the type (in square brackets) times how many items will be in the array.

names = [str] * 5 # This would eventually store 5 names
ages = [int] * 10 # This would eventually store 10 ages
prices = [float] * 7 # This would eventually store 7 prices
answers = [bool] * 4 # This would eventually hold 4 True or False answers

	

With the array created, it is then possible to assign the value. This would be done by accessing the index of each array item and assigning it a value.

names[0] = "John"
names[1] = "Mary"
names[2] = "Betty"
names[3] = "David"
names[4] = "Sam"

This then becomes more efficient when looping through the array and allowing the user to enter and assign the values

# Creating an array of strings called names that holds 5 names
names = [str] * 5 

for i in range(len(names)): # loop through all 5 array positions
    # Ask the user to enter a name and store it at the current position
    names[i] = str(input("Enter a name: ")) 

Target

You should be able to use 1-D Arrays to solve a problem.