Press enter to skip the top menu

Python Intermediate

Tuples

NCEA Compatibility

Module: as91883 Develop a computer program

Requirements: Lists

Go to top

Learning Outcomes

On completion of this section you will know the nature of tuples and how to:

Go to top

Introduction

On the previous page we looked at the concept of lists. We discussed that lists were used when we had a large number of data items that required identical processing. For this reason the elements of a list were always the same type.

Tuples on the other hand can contain data items of different types, including other tuples.

One other difference between the two structures is that while lists, can be changed in any way we want, once we have created a tuple we can't change it or its contents. For this reason tuples are used when we want a set of data items that can't be overwritten.

Below we shall look at some basic properties of tuples and how we can use them.

Go to top

A simple Tuple Example

The sample code below is a simple as it gets regarding using tuples.

Listing 1
                        Tuple1 = 5, 7.3, 3.14159266
                        Tuple2 = 225, 783, 6.6666
                        Tuple3 = 'Tom', 'Dick', 'Harry'
                        print(Tuple1)
                        print(Tuple2)
                        print(Tuple3)
                    

Lines 1 - 3 create three simple tuples. Note that for each tuple we simply list the contents, separated by commas.

Unlike the lists the contents are not enclosed in square brackets. It is however a good practice to enclose the tuple's contents in round brackets, although it is not strictly necessary.

Fig 1

Above we see the contents of the three tuples displayed using the print() function. Notice that the function has enclosed the contents of each tuple in round bracket, although those brackets did not exists in the original program.

For the rest of this page we shall follow the convention of enclosing our tuples in brackets.

Go to top

More complex Tuple Example

In Listing 1 above our tuples were very simple: the first two contained only numeric data while the third one contained text. In this example we shall look at tuples containing integers, real numbers, text and other tuples.

Listing 2
                        Tuple1 =(1, 14, 'Jo', 3.14159266, 'Anne')
                        Tuple2 = ('Thomas', ('Annie', 'Mary', 'Kate'))
                        Tuple3 = (Tuple1, Tuple2)
                        Tuple4 = Tuple1 + Tuple2
                        print(len(Tuple1))
                        print(len(Tuple2))
                        print(Tuple3)
                        print(Tuple4)
                    

At line 1 Tuple1 contains two integers, a text item, a real number and, finally, another text item. Thus it contains five elements

At line 2 Tuple2 contains a text item and another tuple. Thus Tuple2 contains only two elements: the first text element 'Thomas' and the second element which is a tuple in it's own right containing the women's names. We know it is a tuple since it is contained within it's own set of brackets.

Line 3 creates another tuple, Tuple3, which contains Tuple1 and Tuple2. Thus Tuple3 contains two tuples, one a copy of Tuple1 and the other a copy of Tuple2

Line 4 creates another tuple, Tuple4. This contains only one tuple. It has seven elements: a copy of the five elements of Tuple1 and the two elements of Tuple2.

Fig 2

Above we see the output of the code in Listing 2:

Go to top

Accessing Tuple Contents

The first two lines of Listing 3 below are the same as those of Listing 2. However the processing we do on the two tuples is very different to what we did in Listing 2.

Listing 3
                        Tuple1 =(1, 14, 'Jo', 3.14159266, 'Anne')
                        Tuple2 = ('Thomas', ('Annie', 'Mary', 'Kate'))
                        print(f'Length of Tuple1 is {len(Tuple1)}')
                        for item in Tuple1:
                            print(item)
                        print(f'Length of Tuple2 is {len(Tuple2)}')
                        for item in Tuple2:
                            print(item)
                    

Lines 4 and 5 is a for loop which iterates through the contents of Tuple1 and prints out the values of each item in that tuple.

Lines 7 and 8 is a similar for loop, which iterates through the contents of Tuple2.

Despite its apparent size Tuple2 has only two elements: the string item 'Thomas' and another tuple with three women's names.

The output is shown in Fig 3 below.

Fig 3
Go to top

Data Types

Once again the first two lines of Listing 4 below are identical to their equivalents in Listing 3 and Listing 2. The rest of the code is also quite similar to that in Listing 3.

The sole difference is that lines 5 and 7 use the type() function to print the data type of the current item.

As we stated earlier tuples can hold different data types. This means that we occasionally need to be able to distinguish the different types. We do this using the type() function as shown in lines 5 and 7 of Listing 4.

Listing 4
                        Tuple1 =(1, 14, 'Jo', 3.14159266, 'Anne')
                        Tuple2 = ('Thomas', ('Annie', 'Mary', 'Kate'))
                        print(f'Length of Tuple1 is {len(Tuple1)}')
                        for item in Tuple1:
                            print(f'{item}   {type(item)}')
                        print(f'Length of Tuple2 is {len(Tuple2)}')
                            print(f'{item}   {type(item)}')         
                    

Below is the output of Listing 4. Notice that alongside the value of each element, the element's type is also displayed.

Fig 4

Listing 5 below shows another way of using the type() function.

Listing 5
                        Tuple1 = ('Thomas', ('Annie', 'Mary', 'Kate'),14, 'Jo', 3.14159266, 'Anne')
                        for item in Tuple1:
                            if type(item) is int:
                                print(f'{item} is of type int')
                            elif type(item) is float:
                                print(f'{item} is of type float')
                            elif type(item) is str:
                                print(f'{item} is of type string')
                            elif type(item) is tuple:
                                print(f'{item} is of type tuple')
                            else: 
                                print(f'{item} is of type list')
                    

An if..elif..else construct is used to test each element of a tuple to determine whether it is an integer, real number, string, tuple or list.

Fig 5
Go to top

Nested Tuples

So far we have seen that as well as holding different data types, tuples can also hold other tuples. They also hold lists.

When displaying the contents of a tuple we were only able to show a nested tuple with its contents enclosed by curly brackets. Here we shall use nested for loops in order to print the contents of nested loops.

Listing 6
                        Tuple1 = ('Thomas', ('Annie', 'Mary', 'Kate'),14, 'Jo', 3.14159266, 'Anne', ['Tom', 'Dick', 'Harry'])
                        print(f'{Tuple1}\n')
                        for item in Tuple1:
                            if type(item) is int:
                                print(f'{item} is of type int')
                            elif type(item) is float:
                                print(f'{item} is of type float')
                            elif type(item) is str:
                                print(f'{item} is of type string')
                            elif type(item) is tuple or type(item) is list :
                                print('\nBelow are the contents of a nested tuple or list')
                                for TupleItem in item:
                                    print(f'      {TupleItem} - {type(TupleItem)}')
                                print('\n')
                            else: 
                                print('Item type is unknown')
                    

In line 1 of Listing 6 we have a tuple that contains three string items, one integer item, one floating point item, one tuple which contains women's names and one list which contains men's names.

Apart from lines 1 and 2 the rest of the program consists of a for loop that spans lines 3 to 16. The body of this loop consists of an if..elif..else construct.

The code spanning lines 4 - 9 should be familiar to us by now and therefore there is no need to elaborate on it. We shall therefore concentrate on the code following line 9.

At line 10 the current item is tested for being either a tuple or a list. If it is then the block of code spanning lines 11 - 14 is executed.

Line 11 prints a heading indicating that the following display forms the contents of a nested loop.

Lines 12 and 13 form a nested for loop inside the main loop. Line 12 iterates through the item, which may be an tuple or a list. Line 13 prints the value and the type of the sub-item

Notice at line 13 that there is a blank area of 6 spaces before anything is printed. This is in order to indent the contents of the tuple/list. This indentation indicates that they are contents of a sub-list or sub-tuple.

Fig 6

Fig 6 above shows the output of Listing 6.

Go to top

Use of Tuples

Up to now we have been looking at the nature of tuples. Here, however we shall look at how to use tuples as part of a program.

Returning multiple values from a function

A function can return only one value to the program that calls it. We can however use tuples to get multiple values from a function; we simply create a tuple with the values we wish to return and then return the tuple itself. This is what we do in Fig 7 below.

Listing 7
                        #Use of Tuples
                        def calculatePay(hrs, rte):
                            gross = hrs *rte
                            tax= gross * 0.25
                            net = gross - tax
                            rTuple = (gross, tax, net,)
                            return rTuple
                        
                        floatHours = float(input("Enter hours worked"))
                        floatRate = float(input("Enter hourly rate"))
                        payData = calculatePay(floatHours, floatRate)
                        print(payData)
                    

This is a very simplified version of the payroll applications that we have been working with so far. It consists of a function named calculatePay() which spans lines 2 - 7 and the main body which spans lines 9 - 12.

Lines 9 and 10 form the input section of the program by getting the values of hours and rate from the user.

Line 11 calls the function calculatePay() and passes to it the values of the hours and rate that have been received from the user.

At line 3 those values are used to calculate the gross pay and the result stored in the variable gross, while at lines 4 and 5 the tax and net are calculated and stored in the local variables tax and net.

By now we have the results of the calculation stored in the local variables gross, tax and net. Our next task is to return them back to the main program. We do this in two steps as follows:

At line 11 the new tuple is stored in the variable payData.

Line 12 prints the raw tuple.

Fig 7

Although the above program works correctly, its output leaves a lot to be desired; three numeric values separated by commas does not tell us much. In the next example we shall extract the separate elements of the tuple and add labels to them in order to give a more accessible output.

Listing 8
                        #Use of Tuples
                        def calculatePay(hrs, rte):
                            gross = hrs *rte
                            tax= gross * 0.25
                            net = gross - tax
                            rTuple = (gross, tax, net,)
                            return rTuple
                        
                        floatHours = float(input("Enter hours worked" ))
                        floatRate = float(input("Enter hourly rate"))
                        payData = calculatePay(floatHours, floatRate)
                        print(f'Gross: {payData[0]}\nTax: {payData[1]}\nNet::{payData[2]}')
                    

Listing 8 is identical to Listing 7, apart from Line 12 where the individual components of the of the tuple payData are extracted by their position in the tuple. This gives a more understandable output than that in the previous example.

Fig 8: shows the improved output due to the components of the tuple payData being individually extracted and labelled
Listing 9
                        #Use of Tuples
                        def calculatePay(hrs, rte):
                            gross = hrs *rte
                            tax= gross * 0.25
                            net = gross - tax
                            rTuple = (gross, tax, net,)
                            return rTuple
                        
                        lstTuples= []
                        strEmpName = input("Enter employee name: ")
                        while strEmpName !="":
                            floatHours = float(input("Enter hours worked: " ))
                            floatRate = float(input("Enter hourly rate: "))
                            payData = calculatePay(floatHours, floatRate)
                            tupleTemp = (strEmpName, floatHours, floatRate, payData)
                            lstTuples.append(tupleTemp)
                            strEmpName = input("Enter employee name: ")
                        print("\n**********Output**********")
                        for intCounter in range(len(lstTuples)):
                            print(f'Employee name: {lstTuples[intCounter][0]}\nHours worked: {lstTuples[intCounter][1]}\nHourly rate: {lstTuples[intCounter][2]}\n')
                            print(f'Gross pay: {lstTuples[intCounter][3][0]}\nTax deducted: {lstTuples[intCounter][3][1]}\nNet pay: {lstTuples[intCounter][3][2]}')
                    

Fig 9

If we need a large number of values that cannot be altered, then our best option is to use tuples .

Below is a summary of the key points we have covered in this section:

  • Tuples are stored in memory the same as lists
  • Tuples can have multiple elements and elements can be of different data types.
  • Once created new elements cannot be added to a tuple nor can any element be removed.
  • Each element of a list has its own unique index
  • As well as text and numeric data items, lists and other tuples can be elements of a tuple.
Go to top

Revision

Multi choice

Fill the blanks

Go to top