Back

An introduction to tuples - Answers

Q1. Lists use square brackets. Tuples use round ones.
Q2. farmAnimals[3] = 'chicken'
Q3. TypeError: 'tuple' object does not support item assignment
Q4. The program tries to change the 4th element 'Pig' into 'chicken', which it can't do because farmAnimals is a tuple not a list.
Q5. Highlight the code you want to comment out and then press ALT 3 to comment it out, and ALT 4 to comment it back in again. You can also use the options on the Format menu.
Q6. Once farmAnimals[3] = 'chicken' has been commented out, the program works correctly.
Q7. The program prints out how many elements there are in the farmAnimals tuple, and then all the elements in the tuple, and it does this twice.
Q8. Programmers usually always start counting from zero. The first element in a tuple is therefore element zero.
Q9. Add the line print (farmAnimals[0]) to the end of the program.
Q10. The line print ('\n') prints a line space. 
Q11. This data structure names = 'Dave', 'Fred', 'Mary', 'Ali' is also a tuple. The round brackets in Python is nearly always used by convention, but a tuple can be declared without using brackets.

Q12. This code assigns the elements in the tuple to the variables in the order they are given. a is assigned to green, b is assigned to blue and c is assigned to white.

colours = 'green', 'blue, 'white'
a, b, c = colours

Q13. When you run this code ....

colours = 'green', 'blue', 'white', 'red'
a, b, c = colours
print(a, b, c)

.... you will get an error. The number of elements in the tuple must match exactly the number of variables.

Q14. Functions return only one value. If we make that value a tuple, however, we can return more than one value. Get this code working:

import math
def circles(rad):
""" Return (circumference, area) of a circle with radius rad """
    cir = 2 * math.pi * rad
    area = math.pi * rad * rad
    return (cir, area)

print(circles(3))

Notice that one value is returned from the function, a tuple. The tuple contains multiple values, however!

Q15. How can you access each value returned from a function in a tuple? Get this code working. 

import math
def circles(rad):
""" Return (circumference, area) of a circle with radius rad """
    cir = 2 * math.pi * rad
    area = math.pi * rad * rad
    return (cir, area)

temp = circles(3)
print('Circumference is',temp[0])
print('Radius is',temp[1])

As you can see, you first of all store the tuple returned from the function. Then you access each element in the normal way, by refering to each element's index.

Q16. You can pass tuples as an argument to a function. Here is an example;

colours = ('green', 'blue', 'white', 'red')

def print_col(my_colours):
    for c in my_colours:
    print(c)

print_col(colours)

This code prints out each element in the tuple.

Back