2D lists

List of lists (2D List)

In a 2D list, each item is a list.

groceries = [ ["apples",  "bananas"],
            ["milk", "eggs"]]

How do we retrieve a sublist:

groceries[0]
['apples', 'bananas']

How to retrieve an item in a sublist:

groceries[0][1]
'bananas'

How to append sublists to a list - sol 1

We will create 3 sublists of 5 items each, for that we need nested loops:

# start with an empty list
two_d_list = []
repeat = 3
while repeat > 0:
  # each sublist starts as a new list
  sublist = []
  index = 0
  while index < 5: # 5 items per list
    sublist.append(index)
    index += 1
  # after the inner while loop, append the sublist to the main list
  two_d_list.append(sublist)
  repeat -= 1
  
print(two_d_list)
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

How to append sublists to a list - sol 2

two_d_list = []
repeat = 0
while repeat < 3:
    sublist = []
    index = 0
    while index < 5:
        sublist.append(index)
        index += 1
    two_d_list.append(sublist)
    repeat += 1

print(two_d_list)
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

random module

We start by importing random.

import random

Then we set a seed for replicable results and let’s generate a random integer:

random.seed(123)
result = random.randint(1, 4)
print(result)
1

Short Project

Instructions for Short Project of the Week