Using Tuples


Since tuples are simply another kind of sequence, everything you learned about sequences from strings works with tuples. You can get the length of a tuple, print each element with a for loop, and use the in operator to test if 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. Figure 4.12 shows a sample run of the program.

click to expand
Figure 4.12: The hero's inventory is a tuple, which means it can be counted, indexed, sliced, and even concatenated with another tuple.

Since this program is a little long, I'll go through the code one section at a time rather than show you the whole thing at once. But check out the CD to see the program in its entirety.

Setting Up the Program

The first part of the program works just like it did in the previous program, Hero's Inventory. These lines create a tuple and print out each element:

 # Hero's Inventory 2.0 # Demonstrates tuples # Michael Dawson - 1/29/03 # create a tuple with some items and display with a for loop inventory = ("sword",              "armor",              "shield",              "healing potion") print "Your items:" for item in inventory:     print item raw_input("\nPress the enter key to continue.") 

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 parentheses. The function returns the number of elements in the tuple. Empty tuples, or any empty sequences 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.") 

Since this tuple has four elements (the four strings: "sword", "armor", "shield", and "healing potion"), the message You have 4 items in your possession. is displayed.

TRAP

Notice that in the tuple inventory, the string "healing potion" is counted as a single element, even though it's two words. A single string is always considered one element in a tuple, no matter how many individual words are in it.

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 if 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] 

Figure 4.13 shows this tuple with index numbers.

click to expand
Figure 4.13: Each string is a single element in the tuple.

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 in this chapter, I let the user pick the beginning and ending position numbers. 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] raw_input("\nPress the enter key to continue.") 

Using this tuple as an example, Figure 4.14 provides a visual way to understand tuple slicing.

click to expand
Figure 4.14: Slicing positions for tuples are defined between elements, just as they are for strings.

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] = "battleax" Traceback (most recent call last):   File "<pyshell#3>", line 1, in ?     inventory[0] = "battleax" TypeError: object doesn't support item assignment 

Although you can't change tuples, like strings, you can create new tuples from existing ones.

Concatenating Tuples

You can concatenate tuples the same way you concatenate strings. You simply join them together with +, the concatenation operator:

 # concatenate 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 elements "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 inventory. I did not modify the original tuple assigned to inventory (since that's impossible, 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.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net