Using Lists


Lists are sequences, just like tuples, but lists are mutable. They can be modified. So, lists can do everything tuples can, plus more. Lists work just like tuples, so everything you learned about tuples is applicable to lists, which makes learning to use them a snap.

Introducing the Hero's Inventory 3.0 Program

This program is based on the Hero's Inventory 2.0 program, introduced in Chapter 4, section "Creating Tuples." But instead of using tuples to store the hero's inventory, this program uses lists. The first part of Hero's Inventory 3.0 creates the same results as version 2.0. In fact, the code is almost exactly the same. The only difference is that it uses lists instead of tuples. Figure 5.4 shows off the results of the first part of the program. The second part of the program takes advantage of the mutability of lists and does some brand-new things with sequences. Figure 5.5 shows that part in action.

click to expand
Figure 5.4: The hero's inventory is now represented by a list. The results look almost exactly the same as when the inventory was represented by a tuple in Hero's Inventory 2.0.

click to expand
Figure 5.5: Since the hero's inventory is represented by a list, items can be added, modified, and deleted.

Creating a List

The first line of the program creates a new list, assigns it to inventory, and prints each element. The last line waits for the user before continuing. This works almost exactly like it did in Hero's Inventory 2.0. The only difference is that I surrounded the elements with square brackets instead of parentheses, to create a list instead of a tuple.

 # Hero's Inventory # Demonstrates lists # Michael Dawson - 1/29/03 # create a list 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 Lists

The following code is exactly the same as the corresponding code in Hero's Inventory 2.0:

 # get the length of a list print "You have", len(inventory), "items in your possession." raw_input("\nPress the enter key to continue.") 

Using the in Operator with Lists

Again, the code for this section is exactly the same as in the older version. The in operator works the same with lists as it does with tuples.

 # test for membership with in if "healing potion" in inventory:     print "You will live to fight another day." 

Indexing Lists

Once again, the code is exactly the same as it was with tuples. Indexing a list is the same as indexing a tuple: just supply the position number of the element you're after in brackets.

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

Slicing Lists

Would you believe that slicing a list is exactly the same as slicing a tuple? Again, you just supply the two end points, separated by a colon, in brackets:

 # 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.") 

Concatenating Lists

Concatenating lists works the same way concatenating tuples does. The only real difference here is that I created a list (rather than a tuple) and assigned it to chest. This is a small but important difference, because you can only concatenate sequences of the same type.

 # concatenate two lists chest = ["gold", "gems"] print "You find a chest which 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("\nPress the enter key to continue.") 

Understanding List Mutability

At this point, you may be getting a bit tired of reading the phrase "works exactly the same as it did with tuples." So far, with the exception of using brackets instead of parentheses, lists seem no different than tuples. But there is one huge difference between them. Lists are mutable. They can change. This makes lists the most powerful and flexible sequence type at your disposal. Since lists are mutable, there are many things you can do with them that you can't do with tuples.

Assigning a New List Element by Index

Because lists are mutable, you can assign an existing element a new value:

 # assign by index print "You trade your sword for a crossbow." inventory[0] = "crossbow" print "Your inventory is now:" print inventory raw_input("\nPress the enter key to continue.") 

The following line assigns the string "crossbow" to the element in inventory at position 0:

 inventory[0] = "crossbow" 

The new string replaces the previous value (which was "sword"). You can see the results when the print statement displays the new version of inventory.

TRAP

You can assign an existing list element a new value with indexing, but you can't create a new element in this way. An attempt to assign a value to a nonexistent element will result in an error.

Assigning a New List Slice

In addition to assigning a new value to a single element, you can assign a new value to a slice. I assigned the list ["orb of future telling"] to the slice inventory[4:6]:

 # assign by slice print "You use your gold and gems to buy an orb of future telling." inventory[4:6] = ["orb of future telling"] print "Your inventory is now:" print inventory raw_input("\nPress the enter key to continue.") 

This assignment statement replaces the two items inventory[4] and inventory[5] with the string "orb of future telling". Because I assigned a list with one element to a slice with two elements, the length of the list shrunk by one.

Deleting a List Element

You can delete an element from a list with the del command. Just designate the element after the del command:

 # delete an element print "In a great battle, your shield is destroyed." del inventory[2] print "Your inventory is now:" print inventory raw_input("\nPress the enter key to continue.") 

After this code executes, the element that was at position number 2, the string "shield", is removed from inventory. Deleting an element doesn't create a gap in a sequence. All the elements after the deleted one "slide down" one position. So, in this case, there is still an element in position 2, it's just the element that was at position 3.

Deleting a List Slice

You can also delete a slice from a list:

 # delete a slice print "Your crossbow and armor are stolen by thieves." del inventory[:2] print "Your inventory is now:" print inventory raw_input("\n\nPress the enter key to exit.") 

The following line removes the slice inventory[:2], which is ["crossbow", "armor"], from inventory:

 del inventory[:2] 

Just as with deleting an element, the remaining elements form a new, continuous list, starting from position 0.




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