0% found this document useful (0 votes)
19 views28 pages

L07 - Arrays

Uploaded by

Kevin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views28 pages

L07 - Arrays

Uploaded by

Kevin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Introduction to Programming

Semester 1, 2021
Lecture 7,
Array

Slides based on material by John Stavrakakis and that provided for


Sections 1.4 ofSedgewick . All rights reserved
Copyright Warning

COMMONWEALTH OF AUSTRALIA

Copyright Regulations 1969

WARNING

This material has been reproduced and communicated to you by or


on behalf of the University of Sydney pursuant to Part VB of the
Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright


under the Act. Any further reproduction or communication of this
material by you may be the subject of copyright protection under
the Act.

Do not remove this notice.

2
Week 4: Arrays

We will cover: Array. Create and access arrays. Array of objects.


You should read: §§1.4 of Sedgewick

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

Store group of data related to each other:

e.g. states= [‘nsw’, ‘qld’, ‘vic’, ‘nt’, ‘wa’, ‘sa’]


7
Store order of data

The order of data sometimes is important:

e.g. Students book for the helpdesk and consultation time:

helpdesk=[student1, student2, student3,…..student6]

consultation= [student10, student11, student12, ….student16]


8
Information of the same type

 Write a program that displays the name of 50 students


 Write a program that calculates and displays the total from 100
values
 Write a program that counts how many people in this room have
a birthday today

What is the data type for each problem?

If we write these programs, we need to use one variable to store each


value

9
Data Structure

› Data Structure

› Organizing and storing data in Python

›Arrays , Lists

10
Arrays

An array is a contiguous block of memory containing multiple


values of the same type.

Array solves the problem of having many variables.


e.g. you don’t have to declare 100 int variables.

1 # bad style bro


2 value001 = 32
3 value002 = 18
4 value003 = 4
5 ...
6 value100 = 6

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 need to first understand the principle of arrays to


understand how to use the list data structure.

Python presents the usage of a list as an array. However, lists have


different operations and internal memory organization.

We will first present the array ideas , then the list ideas.

12
Array

Var_Name a

Values 1 2 3 …… 10

Index a[0] a[1] a[2] a[3….8] a[9]

13
Arrays —creation

A list is specified as two square brackets [ and ]. An empty array


1 x=[ ]

Obtaining the length of the array


1 x_len = len(x)

Printing the empty array


1 p r i n t ( " the array i s : " + s t r ( x) )
2 p r i n t ( " the length of t h i s array i s : " + s t r ( l e n ( x) ) )

There is not much to do with an empty array. We still need it


 It is used to describe the data type (initial value is a list)
 It is defining a collection of things, where it represents an empty
collection
 As we will see, it is useful for further operations with lists 14
Arrays — creation (cont.)

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.)

A two element array

1 x = [ 47 , 25 ]

Values 47 25

Index x[0] x[1]

A multi-element array is defined as comma separated objects of the


same type within the square brackets [ and ]

1 x = [ -3 , -2 , -1 , 0 , 1 ]

Values -3 -2 -1 0 1

Index x[0] x[1] x[2] x[3] a[4]


Arrays — creation (cont.)

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

Index x[0] x[1] x[2] x[3] a[4]


Arrays — Initialisation

Initialise each value of the array at declaration

names = [ " Bill", " Ted", " Larry"]


print( names [0])
print( names [1])
print( names [2])
18is / 46
INFO1110 2020 S2 Dr. John Stavrakak

Values Bill Ted Larry

Index names[0] names[1] names[2]

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

The array contains multiple values of the same type

Each element of the array is described by an index number.

The numbering starts at 0, not 1. The first element of the array is


referred to as the “the zero-th element” or “0th element” of the array.

To access the ith element of an array A we just use A[i].

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

[1]Write a program to test this behaviour: see what happens.


Using the array

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

Index values[0] values[1] values[2] values[3]


ArrayOfStrings.py

1 import sys i = 0
2 while i < len ( sys. argv ):
3 argument = sys. argv [ i]
4 print( argument)
5 i=i+1

Running this gives the following behaviour:


~> python ArrayOfStrings.py one two
ArrayOfStrings.py
one
two
Arrays of objects

You can have arrays of anything: we have used int type and String
type, but consistently.

As the programmer, you are deciding what memory you need to


have and then how it is processed.
 Print an array of integers
 Print an array of strings
 Print a mixed array of integers and strings … oh wait … does
this work?

Mixing different objects into the same array can become


problematic. There are quick and dirty solutions to this,
however, they make both testing and debugging much harder.

Use the same type of object in your arrays!


Array module in Python

How to create an Array in Python:


importing the array module as follows :
import array as arr
arr is the alias name for ease of use
Data type can be int, float, double, etc

Import without alias


from array import *
from array import array
This means you want to import all functions from the array module.
Arrays syntax

Syntax:

from array import array


a = array(‘d’, [3.1, 4.2, 5.6])

The first parameter ‘d’ is a data type float and the values are specified as the
next parameter.

a = array(data type, value list) #when you import using array


Arrays data type

various data types and their codes.

Type code Python Data Type Byte size


i int 2
I int 2
u unicode character 2
h int 2
H int 2
l int 4
L int 4
f float 4
d float 8
Accessing Arrays elements

Syntax:

Array_name [ index value ]

a = array(‘d’, [3.1, 4.2, 5.6])

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.

NumPy arrays support different data types.

To create a NumPy array, you need to specify the items enclosed in


square brackets

import numpy as np

array_a = np.array([“numbers”,1, 3, 5, 7, 99 ])
print (array_a)

[‘numbers’ ‘1’ ‘3’ ‘5’ ‘7’ ‘99’]


Demo

Array1 - using array module

Array2 - using NumPy package

Array3 - using list in Python

You might also like