Back

More examples of using for loops

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. What does this code do?
Q3. What is the purpose of end=' '?
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. What is printed out when you run the above code?
Q6. Here is an exta list:

extra =['eye', 'nose', 'mouth']

Add this extra list to your program code and then by using an appropriate list method, add it as an extra element to newData. 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 the extra element has been added correctly.
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.
Q8. Add extra code to print out the third element in the first list.
Q9. Add extra code to print out the first element in the second list.
Q10. Change the element of body parts so that it is ear not eye. Print out the lists to check that the change has taken place correctly.

Back