Computer Programming
Unit 2
Tuples Tutorial
Directions: Read the following Tutorial THOUROUGHLY. Be sure to work through ALL of the examples. You will need to know how to apply these concepts to your own programs.
Creating Tuples
Tuples are a type of sequence, like strings. But unlike string, which can only contain characters, tuples can contain elements of any type. That means you can have a tuple that stores a bunch of high scores for a game, or one that stores a group of employee names.
The nice thing about tuples is that they don’t have to be all of the same type. You can create a tuple with both strings and numbers, if you wanted. And you don’t have to stop at strings and numbers. You can create a tuple that contains a sequence of graphic images, sound files, or even a group of aliens (you’ll learn this later). Whatever you can assign to a variable, you can group together and store as a sequence in a tuple.
Introducing the Hero’s Inventory Program
Hero’s Inventory maintains the inventory of a hero from a typical role-playing game. Like most role-playing games ever created, the hero is from a small, insignificant village. His father was, of course, killed by an evil warlord. And now the hero has come of age. It’s time for him to seek his revenge.
In this program, the hero’s inventory is represented by a tuple. The tuple contains strings, one for each item in the hero’s possession. The hero starts out with nothing, but then I give him a few items.
Here is the code:
# Name
# September 30, 2009
# heroInventory.py
# Demonstrates tuple creation
# create an empty tuple
def main():
inventory = ()
# treat the tuple as a condition
if not inventory:
print "You are empty-handed."
raw_input("\nPress the enter key to continue.")
# create a tuple with some items
inventory = ("sword",
"armor",
"shield",
"healing potion")
# print the tuple
print "\nThe tuple inventory is:\n", inventory
# print each element in the tuple
print "\nYour items:"
for item in inventory:
print item
raw_input("\n\nPress the enter key to exit.")
main()
Creating an Empty Tuple
To create a tuple you just surround a sequence of values, separated by commas, with parentheses. Even a pair of lone parentheses is a valid (but empty) tuple. I created an empty tuple in the first part of the program to represent that the hero has nothing:
inventory = ()
Treating a Tuple as a Condition
When you learn about conditions, you saw that you could treat any value in Python as a condition. That means you can treat a tuple as a condition, too. And that’s what I did in the next line:
if not inventory:
print "You are empty-handed."
As a condition, an empty tuple is false. A tuple with at least one element is true. Because the tuple assigned to inventory is empty, it’s false. That means that not inventory is true. So the computer goes into the if statement and prints the string, “You are empty-handed.”
Creating a Tuple with Elements
An unarmed hero is a boring hero. So next, I created a new tuple with string elements that represent useful items for our hero. I assigned this new tuple to inventory with the following lines:
inventory = ("sword",
"armor",
"shield",
"healing potion")
Each element in the tuple is separated by a comma. That makes the first element the string “sword”, the next “armor”, the next “shield”, and the last element “healing potion”. So each string is a single element in the tuple.
Also notice that the tuple spans multiple lines. You can write a tuple in one line or span it across multiple lines like I did, as long as you end each line after a comma.
Printing a Tuple
Though a tuple can contain many elements, you can print the entire tuple just like you would any single value. That’s what I did in the next line:
print "\nThe tuple inventory is:\n", inventory
The computer displays all the elements, surrounded by parentheses.
Looping through a Tuple’s Elements
Finally, I wrote a for loop to march through the elements in inventory and print each one individually:
print "\nYour items:"
for item in inventory:
print item
This loop prints each element in inventory on a separate line. This loop looks just like the ones you’ve seen with strings.
Remember just because this particular tuple happens to contain all strings it doesn’t mean that they always do. You can create a tuple with integers, floats, and strings if you like.
SIDE NOTE: Other programming language offer structures similar to tuples. Some go by the name “arrays” or “vectors”. However, these other language usually restrict the elements of the sequence to just one type.
Using Tuples
Because tuple are simply another sequence, everything you learned about sequences from strings work with tuples. You can get the length of a tuple, print each element with a for loop, and use the in operator to test whether an element is in a tuple. You can index, slice, and concatenate tuples, too.
Introducing the Hero’s Inventory 2.0
Our hero’s journey continues. In this program, his inventory is counted, tested, indexed, and sliced. Our hero will also happen upon a chest with items in it (represented by another tuple). Through tuple concatenation, our hero’s inventory will be replaced with all of his current items plus the treasure he finds in the chest.
# Name
# September 30, 2009
# heroInventory2.py
# Demonstrates tuples
# create a tuple with some items and display with a for loop
def main():
inventory = ("sword",
"armor",
"shield",
"healing potion")
print "Your items:"
for item in inventory:
print item
raw_input("\nPress the enter key to continue.")
# get the length of a tuple
print "You have", len(inventory), "items in your possession."
raw_input("\nPress the enter key to continue.")
# test for membership with in
if "healing potion" in inventory:
print "You will live to fight another day."
# display one item through an index
index = int(raw_input("\nEnter the index number for an item in inventory: "))
print "At index", index, "is", inventory[index]
# display a slice
begin = int(raw_input("\nEnter the index number to begin a slice: "))
end = int(raw_input("Enter the index number to end the slice: "))
print "inventory[", begin, ":", end, "]\t\t",
print inventory[begin:end]
raw_input("\nPress the enter key to continue.")
# concatinate two tuples
chest = ("gold", "gems")
print "You find a chest. It contains:"
print chest
print "You add the contents of the chest to your inventory."
inventory += chest
print "Your inventory is now:"
print inventory
raw_input("\n\nPress the enter key to exit.")
main()
Using the len() Function with Tuples
The len() function works with tuples just the way it does with strings. If you want to know the length of a tuple, place it inside the parantheses. The function returns the number of elements in the tuple. Empty tuples, or any empty sequence for that matter, have a length of 0. The following lines use the len() function with the tuple:
# get the length of a tuple
print "You have", len(inventory), "items in your possession."
raw_input("\nPress the enter key to continue.")
Because the tuple has four elements, the message You have 4 items in your possession, is displayed.
Notice, in the tuple inventory, the string “healing potion” is counted as a single element even though it is two words.
Using the in Operator with Tuples
Just like with strings, you can use the in operator with tuples to test for element membership. And just like before, the in operator is usually used to create a condition. That’s how I used it here:
# test for membership with in
if "healing potion" in inventory:
print "You will live to fight another day."
The condition “healing potion” in inventory tests whether the entire string, “healing potion” is an element in inventory. Since it is, the message “You will live to fight another day”, is displayed.
Indexing Tuples
Indexing tuples works like indexing strings. You specify a position number, in brackets, to access a particular element. In the following lines, I let the user choose the index number and then the computer displays the corresponding element:
# display one item through an index
index = int(raw_input("\nEnter the index number for an item in inventory: "))
print "At index", index, "is", inventory[index]
The following figure shows this tuple with index numbers.
0
|
1
|
2
|
3
|
“sword”
|
“armor”
|
“shield”
|
“healing potion”
|
-4
|
-3
|
-2
|
-1
|
Slicing Tuples
Slicing works just like you saw with strings. You give a beginning and ending position. The result is a tuple containing every element between those two positions.
Just as in the Pizza Slicer program from earlier, I let the user pick the beginning and ending position number. Then, like before, the program displays the slice:
# display a slice
begin = int(raw_input("\nEnter the index number to begin a slice: "))
end = int(raw_input("Enter the index number to end the slice: "))
print "inventory[", begin, ":", end, "]\t\t",
print inventory[begin:end]
The following figure provides a visual way to understand tuple slicing.
0 1 2 3 4
“sword”
|
“armor”
|
“shield”
|
“healing potion”
|
-4 -3 -2 -1
Understanding Tuple Immutability
Like strings, tuples are immutable. That means you can’t change a tuple. Here’s an interactive session to prove my point:
>>> inventory = ("sword", "armor", "shield", "healing potion")
>>> print inventory
('sword', 'armor', 'shield', 'healing potion')
>>> inventory [0] = "rope"
Traceback (most recent call last):
File "
", line 1, in
inventory [0] = "rope"
TypeError: 'tuple' object does not support item assignment
Concatenating Tuples
You can concatenate tuples the same way you concatenate strings. You can simply join them together with +, the concatenation operator:
# concatinate two tuples
chest = ("gold", "gems")
print "You find a chest. It contains:"
print chest
print "You add the contents of the chest to your inventory."
inventory += chest
print "Your inventory is now:"
print inventory
raw_input("\n\nPress the enter key to exit.")
The first thing I did was create a new tuple, chest, with the two string element “gold” and “gems”. Next, I printed chest to show its elements. After that, I used an augmented assignment operator to concatenate inventory with chest and assign the result back to invevntory. I did not modify the original tuple assigned to inventory (because that is imposible because tuples are immutable). Instead, the augmented assignment operator created a brand new tuple with the elements from inventory and chest and assigned that to inventory.
Share with your friends: |