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. Learn to Program using Python: Lesson 1, Getting Startedprovides an overall description of this online programming course.
Previous lessons have introduced you to lists, subscriptions, sequences, mutable sequences, mappings, slicings, and tuples.
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.
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 immutablesequence.
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.
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.
|# File Tuple01.py #——————————- print “Create a simple tuple” aTuple = (3.14,59,”A string”,1024)
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 emphasis.
|Create a simple tuple Print index value 2 A string Print a short slice (3.14, 59, ‘A string’) Print the entire tuple (3.14, 59, ‘A string’, 1024) Figure 2|
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.
|print “Create a simple tuple” aTuple = 3.14,59,”A string”,1024
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. ( Learn to Program Using Python: Lists, Part IIshowed how to use an index in square brackets to access the items in a list.)
|print “Print index value 2” print aTuple Figure 4|
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 (see Learn to Program Using Python: Lists, Part II.) 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.)
|print “Print a short slice” print aTuple[0:3] Figure 5|
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.
|print “Print the entire tuple” print aTuple[:100] Figure 6|
If you are unfamiliar with this slicing syntax, please see the material on slicing in Learn to Program using Python: Strings, Part II
A complete listing of the program is shown in Figure 7.
|# File Tuple01.py # Rev 7/31/00 # Copyright 2000, R. G. Baldwin # Illustrates indexing and # slicing a simple tuple # #——————————- print “Create a simple tuple” aTuple = (3.14,59,”A string”,1024) print “Print index value 2” print aTuple print “Print a short slice” print aTuple[0:3] print “Print the entire tuple” print aTuple[:100] Figure 7|
There is a great deal more to be learned about manipulating tuples, and this will be the topic of future lessons.
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).
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.
|# File Tuple08.py # Rev 7/31/00 # Copyright 2000, R. G. Baldwin # Illustrates creating and # printing a simple tuple #——————————- t1 = “a”,1,”c” print t1 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.
|# File Tuple09.py # Rev 7/31/00 # Copyright 2000, R. G. Baldwin # Illustrates accessing a tuple # item with an index #——————————- t1 = “a”,1,”c” print t1 Figure 9|
10. Write a Python script that shows how to access a slice of a tuple and print it.
Ans: See Figure 10.
|# File Tuple10.py # Rev 7/31/00 # Copyright 2000, R. G. Baldwin # Illustrates accessing a slice # of items from a tuple #——————————- t1 = “a”,”b”,”c”, “d”, “e” print t1[1:4] 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.