Arrays in Python
Arrays in Python
Problem
An Array (a List)
Semantics
Syntax
Meaning
Concatenation
Repetition
Indexing
Length
Slicing
Iteration
Indexing an Array
List Operations
10
List Operations
Method
Meaning
<list>.append(x)
<list>.sort()
<list>.reverse()
<list>.index(x)
<list>.insert(i, x)
<list>.count(x)
<list>.remove(x)
<list>.pop(i)
Deletes the ith element of the list and returns its value.
11
Solution to starting
problem
SIZE = 5
n = [0]*SIZE
total = 0
for ct in range(SIZE):
n[ct] = float(input("enter a number ))
total = total + n[ct]
cont'd on next slide
for i in range(5):
Initialization of arrays
Assigning Values to
Individual
Array
Elements
temps = [0.0] * 5
m=4
temps[2] = 98.6;
temps[3] = 101.2;
temps[0] = 99.4;
temps[m] = temps[3] / 2.0;
temps[1] = temps[3] - 1.2;
// What value is assigned?
7000
99.4
temps[0]
7004
7008
98.6
temps[1]
temps[2]
7012
101.2
temps[3]
7016
50.6
temps[4]
18
7004
7008
7012
7016
temps[0]
temps[1]
temps[2]
temps[3]
temps[4]
19
Indexes
Variable Subscripts
temps = [0.0]*5
m=3
......
What is temps[m + 1] ?
What is temps[m] + 1 ?
7000
100.0
temps[0]
7004
7008
7012
7016
100.2
100.4
100.6
100.8
temps[1]
temps[2]
temps[3]
temps[4]
21
Random access of
elements
ctr[num] +=1
statement
is the crucial
Parallel arrays
Parallel Arrays
Parallel arrays are two or more arrays that
have the same index range and whose
elements contain related information,
possibly of different data types
EXAMPLE
SIZE = 50
idNumber = [ ]*SIZE
hourlyWage = [0.0] *SIZE
arrays
parallel
25
SIZE = 50
idNumber = [ ] *SIZE
hourlyWage =[0.0] *SIZE
idNumber[0]
4562
hourlyWage[0]
9.68
idNumber[1]
1235
hourlyWage[1]
45.75
idNumber[2]
6278
hourlyWage[2]
12.71
.
.
.
.
.
.
.
.
.
.
.
.
idNumber[48]
8754
hourlyWage[48]
67.96
idNumber[49]
2460
hourlyWage[49]
8.97
26
2-dimensional arrays
2-dimensional arrays
syntax
66 64 72 78 85 90 99 105 98 90 88 80
row 2,
col 7
stateHighs[2]
might be
[7]
Arizonas
.
high for
[48]
August
[49]
39
total = 0
for month in range(NUM_MONTHS):
total = total + stateHighs[2][month]
average = round (total / NUM_MONTHS)
average
85
43
Passing an array as an
argument
46
5 DEPTS
rows
S
E
R
O
s
ST eet
3 sh
monthlySales[3][7][0]
sales for electronics in August at White Marsh
12 MONTHS columns
47