= create_list(5, 3)
my_two_d_list 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]]
= create_list(3, 5)
my_two_d_list 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.
= [ ["apples", "bananas"],
groceries "milk", "eggs"]] [
How do we retrieve a sublist:
0] groceries[
['apples', 'bananas']
How to retrieve an item in a sublist:
0][1] groceries[
'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 = 3
repeat while repeat > 0:
# each sublist starts as a new list
= []
sublist = 0
index while index < 5: # 5 items per list
sublist.append(index)+= 1
index # after the inner while loop, append the sublist to the main list
two_d_list.append(sublist)-= 1
repeat
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 = 0
repeat while repeat < 3:
= []
sublist = 0
index while index < 5:
sublist.append(index)+= 1
index
two_d_list.append(sublist)+= 1
repeat
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:
123)
random.seed(= random.randint(1, 4)
result print(result)
1