More examples of using for loops - Answers
Q1. Get the following code working:
#data is a list of five pieces of data.
data = [1,2,3,4,5]
for item in data:
print (item, end=' ')
Q2. This code prints out the numbers 1 - 5 in row, each number separated by a space.
Q3. The purpose of end=' ' is to keep the cursor from moving to the next line, and separating data with a space.
Q4. An element in a list of elements can also be a list. We can systematically work through each element in each of the lists. Get this code working by adding the extra lines to your existing program from Q1:
#data is a list of five pieces of data.
data = [1,2,3,4,5]
for item in data:
print (item, end=' ')
#newData is a list of four pieces of data. Each of the pieces
#of data in newData is itself a list.
print('\n')
newData = [[1.02, 2.02, 3, 4, 5.094], [10,20,30,40,50], ['apples','bananas','pears'],[True,True,False]]
for item in newData:
for datapoint in item:
print(datapoint,end=' ')
print('\n')
Q5.The following is printed out when you run the code:
1 2 3 4 5
1.02 2.02 3 4 5.094
10 20 30 40 50
apples bananas pears
True True False
Q6. The code to append an extra element to a list is:
#This adds an extra element to newData
print('\n')
newData = [[1.02, 2.02, 3, 4, 5.094], [10,20,30,40,50], ['apples','bananas','pears'],[True,True,False]]
extra =['eye', 'nose', 'mouth']
newData.append(extra)
for item in newData:
for datapoint in item:
print(datapoint,end=' ')
print('\n')
Q7. Using an appropriate list method, modify your code to remove the third element in newData ['apples','bananas','pears']. If you are unsure of the method to use, look up 'Python 3 list methods'. Print out all of the items in newData again, to check that this element has been removed correctly.
#This removes the element in the position where the index = 2 (the third position)
print('\n')
newData = [[1.02, 2.02, 3, 4, 5.094], [10,20,30,40,50], ['apples','bananas','pears'],[True,True,False]]
extra =['eye', 'nose', 'mouth']
newData.append(extra)
newData.pop(2)
for item in newData:
for datapoint in item:
print(datapoint,end=' ')
print('\n')
Q8 - Q10 The code is:
print('The third element of the first list is:',newData[0][2])
print('The third element of the first list is:',newData[1][0])
#Change eye to ear and print out the newData list again.
newData[3][0]='ear'
for item in newData:
for datapoint in item:
print(datapoint,end=' ')
print('\n')