You are on page 1of 12

Programming: Arrays

ICT & CS NIS Lagoon


Learning Objectives
We are learning to:

GOOD: Describe an array structure

BETTER: Explain how arrays work in Python

BEST: Create and use arrays in Python

LO: [LO HERE}


Why are variables not enough?
• Computers – process data
• One piece of data = variable
• Real-life programs handle tens of thousands of pieces of data, too
many to store completely separately!
Data Structures
• Data is grouped together/structured in a specific format
• Collection of data is called a data structure
Lists Changeable

Allows
Sequential
duplicates

Can have
Ordered Lists different data
types

e.g. myList = [1,2,3,’four’,5]


Allows
duplicates
Elements do not
Unchangeable need to be same
data type

Ordered Tuples Sequential

myTuple =(10,20,30,40,’fifty’)
Allows
duplicates
Elements are
Changeable same data
type

Ordered Arrays Sequential


Arrays
•  Think of an array a flight of stairs where on each step is placed a
value (let’s say one of your friends). You can identify the location of
any of your friends by simply knowing the count of the step they are
on.
Declaring an Array in Python
• Python does not have arrays – we use lists instead.

e.g. myArray = [“apple”,”banana”,”cherry”]


Array Methods
• append() Adds an element at the end of the list
• clear() Removes all the elements from the list
• count() Returns the number of elements with the specified value
• insert() Adds an element at the specified position
• pop() Removes the element at the specified position
• remove() Removes the first item with the specified value
• reverse() Reverses the order of the list
• sort() Sorts the list
Len() function
• The number of elements in an array can be found out using
• the len() function
Let’s review…

Data structure Arrays


The collection of data structured together in a specific Arrays are a form of data structure used to store
format is called data structure. a set of data elements in a certain order.

Methods involved with arrays


Creating two-dimensional arrays using
• typecode(): returns the type code of an array
program statements
• itemsize(): returns the length in bytes of one array element
A two-dimensional array is created using lists:
• append(): to include an element to the end of an array
• count(x): returns the number of occurrences of element x array2d=[ [elements in row 1], [elements in row
2] and so on]
• index(x): returns the index of the first occurrence of element x
• insert(i, x): inserts a new array element with value x at position
i
• remove(x): removes the first occurrence of element x
• pop(): removes and returns the last element

You might also like