Back

An introduction to tuples

Q1. When we looked at lists, we started by typing in this program:

farmAnimals = ['cow','goat','sheep','pig']
wildAnimals = ['fox', 'rat', 'badger']
data = [2.0, 17, 'horse', True]
newCrops = []

print(len(farmAnimals))
for item in farmAnimals:
    print (item)

farmAnimals[3] = 'chicken'

print('\n')
print(len(farmAnimals))
for item in farmAnimals:
    print (item)

Here is the same program, except it uses tuples, not lists. There is one change we have made to this program (although the same change has been made in a number of places). Can you spot what it is?

farmAnimals = ('cow','goat','sheep','pig')
wildAnimals = ('fox', 'rat', 'badger')
data = (2.0, 17, 'horse', True)
newCrops = ()

print(len(farmAnimals))
for item in farmAnimals:
    print (item)

farmAnimals[3] = 'chicken'

print('\n')
print(len(farmAnimals))
for item in farmAnimals:
    print (item)

Q2. This program partially works, but then fails at a particular line. Which line does the program fail on?
Q3. What error message did you get?
Q4. The key difference between a list of items and a tuple of items is that tuples are 'immutable'. That means that that you cannot change the tuple in any way. Once the tuple has been created, that's it! You can't make any changes to it. Now explain why your program failed on the line that it did.
Q5. How do you 'comment out' a line of code in Python?
Q6. Comment out the line of code that causes the program to fail. Does it work now?
Q7. What does the program do?
Q8. Does the first element in a tuple start at position 0 or position 1?
Q9. Amend the code to print out the first element of the tuple called farmAnimals.
Q10. What does the line print ('\n') do? 
Q11. What kind of data structure does this create: names = 'Dave', 'Fred', 'Mary', 'Ali'
Q12. Explain what this code does:

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

Q13.Explain what happens with the code:

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

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))

Q15. How can you access each value returned as a tuple from a function? 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])

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)

What does this code do?

Back