The purpose of this lab is to gain additional practice working with lists. It explores how to copy (clone) a list and introduces multi-dimensional lists.
list = [1, 2, 3]
newList = list
print(list, newList)
It looks like this code would put the elements of
list into the newList. Add a line
of code after the print statement that changes the second
element of newList to 5. Then print both lists
again. Add a text cell and write down what you saw
happening.clone1, that takes a list
as a parameter and returns a new list that is a clone of the
original list. To create this copy, your function should
first create an empty list. It should then loop through the
original list, and append each element to the new list. When
the loop is finished,the function returns the new list.clone2, that takes a list
as a parameter and returns a new list that is a clone of the
original list. To create this copy, your function should
create an empty list and use the concatenate operator (+) with
the empty new list and the original list. The function should
then return the new list.clone3, that takes a list
as a parameter and returns a new list that is a clone of the
original list. To create this copy, your function should use
slicing on the original list to get all of the elements. Your
function should then return the new list.for loop to iterate over the elements of the list, using one of
these patterns:
for item in list_name: for index in range(len(list_name)):
do something with item do something with list_name[index]
We will use these patterns in the next several exercises. (Try both patterns
for one of the functions below, to see the difference.)
total, that takes a list of numeric values (float
or int) as a parameter and returns the cumulative total of all
elements in the list. The function will need to create a variable
with initial value 0, which will be used to keep track of the total.
This variable will get updated in the body of the loop that iterates
over the elements of the list. At the end of the function, this
variable gets returned. average, that takes a list of
numeric values as input and returns the average of the elements
in the list. This function should look almost exactly like the
total function, but will have one additional
calculation.
import random
# Create 2-dimensional list
values = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
# Fill list with random values
for r in range(len(values)):
for c in range(len(values[0])):
values[r][c] = random.randint(1,100)
# Display the random numbers
print(values)
myList = [[0 for j in range(300)] for i in range(200)]
This will create a list with 200 elements, where each of those
elements is a
list with 300 0s. Type this in and print the list.