## Tuples, Index and Slice

Python Programming Lesson #36

August 15, 2000

## Preface

This document is part of a series of online tutorial lessons designed to teach you how to program using the Python scripting language.

Something for everyone

Beginners start at the beginning, and experienced programmers jump in further along. Lesson 1 provides an overall description of this online programming course.

## Introduction

Previous lessons have introduced you to lists, subscriptions, sequences, mutable sequences, mappings, slicings, and tuples.

Manipulating lists

Those lessons showed you some of the ways that you can manipulate lists.  The discussion was illustrated using sample programs.

Now let's talk about tuples

The introduction to tuples in the previous lesson was very brief.  This and several subsequent lessons use sample programs to show you a variety of ways to manipulate and use tuples.

## What Is a Tuple?

As a practical matter, a tuple is like a list whose values cannot be modified.  In other words, a tuple is immutable.

According to Lutz and Ascher, Learning Python from O'Reilly, tuples are "Ordered collections of arbitrary objects."

Can't be changed in place...

Again according to Lutz and Ascher, "They work exactly like lists, except that tuples can't be changed in place (they're immutble)..."

Parentheses replace square brackets

Unlike lists, however, tuples don't use square brackets for containment.  Rather, they are normally written as a sequence of items contained in parentheses.

An immutable sequence

Like a string or a list, a tuple is a sequence.  Like a string (but unlike a list), a tuple is an immutable sequence.

Tuples can be nested

Tuples can contain other compound objects, including lists, dictionaries, and other tuples.  Hence, tuples can be nested.

An array of references

One way to think of a tuple is to consider it to be an array of references to other objects.

While the tuple itself cannot be changed in place, the values contained in the objects to which it holds references can be changed (assuming that those objects are mutable).

What can you do with a tuple?

You can do just about anything with a tuple that you can do with a list, taking into account the fact that the tuple is immutable.  Therefore, those list operations that change the value of a list in place cannot be performed on a tuple.

Accessed by index
As with strings and lists, items in a tuple are accessed using a numeric idex.  The first item in a tuple is at index value 0.

Why do tuples exist?

Tuples provide some degree of integrity to the data stored in them.  You can pass a tuple around through a program and be confident that its value can't be accidentally changed.  Note, however, that the values stored in the items referred to in a tuple can be changed (more about this later).

In addition, in a future lesson, we will see some sample programs that require the use of tuples.

## A Sample Program

Indexing and Slicing Tuples

Figure 1 shows the beginning of a Python script that first creates, and then manipulates a simple tuple (boldface added for emphasis).  The remainder of this program is shown as code fragments in subsequent figures.  The entire program is shown near the end of the lesson.

Let's see some output

At this point, I am going to show you the output produced by executing the Python script in Figure 1 so that you will have it available for reference during the discussion that follows.

The output is shown in Figure 2 with some lines highlighted using boldface for emplasis.

Tuple syntax

From a syntax viewpoint, you create a tuple by placing a sequence of items inside a pair of enclosing parentheses and separating them by commas. Note that the parentheses can be omitted when such omission will not lead to ambiguity.

The fragment in Figure 1 creates a simple four-item tuple and assigns it to the variable named aTuple.

Different types allowed

Note that the items in a tuple can be different types.  This simple tuple contains a float, an integer, a string, and another integer.

Could omit the parentheses

In this case, the parentheses could be omitted from the tuple syntax, because such omission would not lead to ambiguity.  Figure 3 shows what this code fragment would look like if the parentheses were omitted.  The tuple in Figure 3 was highlighted using boldface for emphasis.

The scripts in Figure 1 and Figure 3 are operationally identical and produce the same output, as shown in Figure 2.

Indexing tuple items

The items in a tuple can be accessed using an index enclosed in square brackets as shown in Figure 4.  (An earlier lesson showed how to use an index in square brackets to access the items in a list.)

Tuple item is printed

The third item in the tuple is accessed and printed in Figure 4(Remember, index values begin with the value 0, so index value 2 points to the third item in the tuple.)

The output produced by the code in Figure 4 is the first boldface line in Figure 2, which reads "A string."

Tuples can be sliced

Tuples can be sliced just like lists.  This is illustrated by the code in Figure 5.

This code uses a slice to access and print the first three items in the tuple.  (Remember, a slice begins with the index shown by the first specified value and ends with the index whose value is one less than the second specified value.)

The output produced by the code in Figure 5 is shown by the second boldface line of output in Figure 2.

Print the entire tuple

Finally, the code fragment in Figure 6 causes the entire tuple to be accessed and printed, as shown by the third boldface line in Figure 2.

If you are unfamiliar with this slicing syntax, please see the material on slicing in a previous lesson.

## Complete Program Listing

A complete listing of the program is shown in Figure 7.

## What's Next?

There is a great deal more to be learned about manipulating tuples, and this will be the topic of future lessons.

## Review

1.  How does a tuple compare with a list?

Ans:  A tuple is like a list whose values cannot be modified.  In other words, a tuple is immutable.

2.  True or false?  A tuple is constructed by enclosing a series of comma-separated items with square brackets.

Ans:  False.  Square brackets are used for this purpose with lists.  Parentheses are used with tuples.

3.  Which if the following is true?

• A.  A tuple is a mutable sequence.
• B.  A tuple is an immutable sequence.
Ans:  B.  A tuple is an immutable sequence.

4.  True or false?  Tuples cannot be nested.

Ans:  False.  Tuples can contain other compound objects, including lists, dictionaries, and other tuples.  Hence, tuples can be nested.

5.  True or false?  The values contained in the objects to which a tuple holds references can be changed (assuming that those objects are mutable).

Ans:  True

6.  True or false?  Those list operations that change the value of a list in place can also be performed on a tuple.

Ans:  False.  Because a tuple is immutable, operations that would change its value in place are not available.

7.  True or false?  The items in a tuple are accessed by key values like a dictionary.

Ans:  False.  Items in a tuple are accessed by numeric index.

8.  Write a Python script that shows how to create and print a simple tuple.

Ans:  See Figure 8.

9.  Write a Python script that shows how to access and print an item in a tuple using a numeric index.

Ans:  See Figure 9.

10.  Write a Python script that shows how to access a slice of a tuple and print it.

Ans:  See Figure 10.

11.  True or false?  All of the items in a tuple must be of the same type.

Ans:  False.  A tuple can contain items of mixed types.

12.  True or false?  The enclosing parentheses must always be used to enclose the items in a tuple.

Ans:  False.  The parentheses can be omitted when this will not lead to ambiguity.

Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

#### About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

-end-