Press enter to skip the top menu

Python Programming

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

Summary

Why we need tuples

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

Nature of tuples

  • 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