my_two_d_list = create_list(5, 3)
print(my_two_d_list)Short Project 7
Creating a 2D list
In this short project, you will create a 2D list or random integers using the .append() method and nested loops (meaning, a loop inside a loop).
Name your file create_two_d_list.py.
Remember to import random and set the seed to 123.
Your function should take a width and length as arguments. The length represents how many sublists you need in your main list. The width is the length of each individual sublist (they are all the same length). Each element in your sublist will be a random integer between 0 and 100.
[[6, 34, 11, 98, 52], [34, 13, 4, 48, 68], [71, 42, 43, 6, 20]]
my_two_d_list = create_list(3, 5)
print(my_two_d_list)[[6, 34, 11], [98, 52, 34], [13, 4, 48], [68, 71, 42], [43, 6, 20]]
This section gives you a quick recap of what we covered in class or introduces any new tips or examples that might help you complete the assignment. Take a few minutes to read through it before you begin.
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 randomThen 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