L07 - Arrays
L07 - Arrays
Semester 1, 2021
Lecture 7,
Array
COMMONWEALTH OF AUSTRALIA
WARNING
2
Week 4: Arrays
3
Lecture 7: Arrays
4
Variable only store single data
5
Group of data
How to store group of data?
E.g. We have 3 subject codes
INFO1110
INFO1910
COMP9001
Others
6
Store Group of data related to each other
9
Data Structure
› Data Structure
›Arrays , Lists
10
Arrays
Idea: Instead of using value046, use the 46th value from the memory of
the array
11
List are not Arrays, Arrays are not Lists - Python
We will first present the array ideas , then the list ideas.
12
Array
Var_Name a
Values 1 2 3 …… 10
13
Arrays —creation
A single elementarray
1 x = [ 47 ]
Values 47
Accessing the only element in the array
Index x[0]
1 f i r s t _ element = x[0]
Printing thearray
1 print(" the array is:" + str(x))
2 print(" the length of this array is: " + str(len( x ) )
3 if len ( x) > 0:
4 print(" the first element of this array is: " + str( x [0]))
oops!
1 second_ element = x [ 1 ]
15
Arrays — creation (cont.)
1 x = [ 47 , 25 ]
Values 47 25
1 x = [ -3 , -2 , -1 , 0 , 1 ]
Values -3 -2 -1 0 1
Accessing eachelement
print(" the array is:" + str( x ) )
print(" the length of this array is: " + str( len ( x ) ) )
if len (x) > 0:
print(" first element is: " + str( len ( x[0] ) ) )
if len (x) > 1:
print(" second element is: " + str( len ( x[1] ) ) )
if len (x) > 2:
print(" third element is: " + str( len ( x[2] ) ) )
if len (x) > 3:
print(" fourth element is: " + str( len ( x[3] ) ) )
if len (x) > 4:
print(" fifth element is: " + str( len ( x[4] ) ) )
Values -3 -2 -1 0 1
which creates an array of String objects, the contents of which are the
three strings “Bill”, “Ted” and “Larry”. The length of the array is set
implicitly to the number of elements in the strings provided in brackets.
Arrays —index
If i is more or less than one whole length of array then Python will throw
an exception [1]
If i is bigger than the array size initialised, Python will throw an exception
Predefine the number of elements in the array using the list operator *
1 values = [0] * 4
2
3 values [0] = 1
4 values [1] = 2
5 values [2] = 3
6 values [3] = 4 20is / 46
INFO1110 2020 S2 Dr. John Stavrakak
7
8 print(" first value: " + str( values [0]))
9 print(" last value: " + str( values [3]))
10
11
sum = values [0] + values [1] + values [2] + values [3]
12
print(" sum : " + str( sum ))
Values 1 2 3 4
1 import sys i = 0
2 while i < len ( sys. argv ):
3 argument = sys. argv [ i]
4 print( argument)
5 i=i+1
You can have arrays of anything: we have used int type and String
type, but consistently.
Syntax:
The first parameter ‘d’ is a data type float and the values are specified as the
next parameter.
Syntax:
a[0] = 3.1
a[1] = 4.2
a[2] = 5.6
NumPy Package
Python provide NumPy Arrays which are a grid of values used in Data
Science.
import numpy as np
array_a = np.array([“numbers”,1, 3, 5, 7, 99 ])
print (array_a)