In [6]:
# to represent 1d data, we can use lists
l = [3,1,4,1,5]
l[2]


Out[6]:
4

In [7]:
# to represent two-dimensional data, we can use lists of lists

# create a 3x3 list of list
a = []
a.append([1,2,3])
a.append([4,5,6])
a.append([7,8,9])
a


Out[7]:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In [8]:
# to fetch an element, fetch the appropriate row list,
# then fetch the column from that row list
a[1][2]


Out[8]:
6

In [9]:
# return the diagonal elements of a list of lists
def diagonal(a):
    d = []
    for i in range(len(a)):
        d.append(a[i][i])
    return d

diagonal(a)


Out[9]:
[1, 5, 9]

In [10]:
# create a 1000 x 1000 matrix of random numbers
from random import random

# create one row
def random1d(n=1000):
    r = []
    for i in range(n):
        r.append(random())
    return r
        
r = random1d()
len(r), r[512]


Out[10]:
(1000, 0.36156756696045045)

In [11]:
# create 1000 rows

def random2d(n=1000):
    rows = []
    for i in range(n):
        rows.append(random1d(n))
    return rows

r = random2d()

len(r), r[512][512]


Out[11]:
(1000, 0.19307087347882979)

In [12]:
# now write the same thing with list comprehensions
def random2d(n=1000):
    return [[random() for j in range(n)] for i in range(n)]

r = random2d()
len(r), r[512][512]


Out[12]:
(1000, 0.8095939381928078)

In [13]:
# let's compute an average of a 2d list of lists

# start with 1d list
def average1d(a):
    s = 0
    for element in a:
        s += element
    return s / len(a)

average1d(random1d())


Out[13]:
0.4916957944532466

In [19]:
# now let's do 2d averaging
def average2d(a):
    # there's no way to tell how many elements
    # there are because each list in the list of lists
    # could be a different length
    n, s = 0, 0
    for row in a:
        for element in row:
            s += element
            n += 1
    return s / n

average2d(random2d())


Out[19]:
0.4998900147940091