One Dimensional Array
• Arrays is a means of storing multiple items of data under one variable/identifier.
• This allows for lots of data to be stored without needing a variable for each item.
• An array is a special variable, which can hold more than one value at a time.
• An array is a collection of items stored at contiguous memory locations. The idea
is to store multiple items of the same type together.
The Length of an Array
Use the len() method/function to return the length of an array . This returns the number
of elements in an array.
Example 1:
What is the data in index 1?
Answer: Blue
What will happen if I change the data in index 3 to Grey?
Answer: The word ‘Green’ would be crossed out and replaced
with ‘Grey’
Example 2: Creating Arrays and accessing elements
Myarr=[10,122,87,7,55,90]
Print(“first element is ”, Myarr[0])
Print(“second element is ”, Myarr[1])
Print(“third element is ”, Myarr[2])
Print(“fourth element is ”, Myarr[3])
Print(“fifth element is ”, Myarr[4])
Print(“sixth element is ”, Myarr[5])
Accessing elements using FOR Loop
Myarr=[10,122,87,7,55,90]
For a in range (0,6):
Print( Myarr[a])
Example 3: myArray = [1, 4, 5, 3, 15, 64, 27, 54]
• Output the second element in the array.
Solution: print(myArray[1])
• Output the data in index 0 in the array.
Solution: print(myArray[0])
• Output the value in index 0 added to the value in index 5.
Solution: print(myArray[0] + myArray[5])
or
firstNum = myArray[0]
secondNum = myArray[5]
total = firstNum + secondNum
print(total)
• Use a count-controlled loop to output each of the array items in turn.
for x in range(0, 8):
print(myArray[x])
Example 4:
Ask a series of questions to check learners’ understanding of this array, for example:
What data is in index 0?
Answer: 30
What is the result of the data in index 2 + the data in index 3?
Answer: 35
What will be output if the pseudocode statement OUTPUT(array[4]) is run?
Answer: 6
How do you access data in an array (list) in Python?
Answer: The array’s identifier [index]
What is the first index in an array?
Answer: 0
What types of bracket do you surround the index with?
Answer: In Python, square brackets are used.
Note:
• The index starts with 0.
• Can easily find any element within the array using the index value