Python
  Home arrow Python arrow Page 4 - Python 101 (part 4): Feeding The Snake
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
VeriSign Whitepapers 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Python 101 (part 4): Feeding The Snake
By: Vikram Vaswani, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 8
    2001-06-25

    Table of Contents:
  • Python 101 (part 4): Feeding The Snake
  • Running The Lights
  • Strange Food
  • Unbreakable
  • Looking Up The Dictionary
  • Of Keys And Locks

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Python 101 (part 4): Feeding The Snake - Unbreakable


    (Page 4 of 6 )

    As you can see, tuples share many of their properties and methods with lists. However, they differ in one very important area: lists are mutable, while tuples are immutable (like strings). It is not possible to alter tuple elements once a tuple has been created; the only way to accomplish this is to create a new tuple containing the new elements.

    >>> listSample = ["red", "green", "blue"] >>> listSample[2] = "pink" >>> listSample ['red', 'green', 'pink'] >>> tupleSample = ("red", "green", "blue") >>> tupleSample[2] = "pink" Traceback (innermost last): File "", line 1, in ? TypeError: object doesn't support item assignment >>>
    A new tuple can be created either by adding two or more existing tuples,

    >>> CreepyCrawlies ('spiders', 'ants', 'lizards') >>> pasta ('macaroni', 'spaghetti', 'lasagne', 'fettucine') >>> strangeFood = CreepyCrawlies + pasta >>> strangeFood ('spiders', 'ants', 'lizards', 'macaroni', 'spaghetti', 'lasagne', 'fettucine') >>>
    or by extracting slices from existing tuples and joining them into a new structure.

    >>> veryStrangeFood = CreepyCrawlies[1], pasta[3], pasta[5] >>> print veryStrangeFood ('ants', 'fettucine', 'rigatoni') >>>
    Or, if you want to be really fancy, you could use the list() and tuple() functions to convert a tuple into a list,

    >>> pasta ('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni') >>> type(pasta) >>> # convert to list >>> pastaList = list(pasta) >>> type(pastaList) >>> print (pastaList) ['macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni'] >>> pastaList[5]="" >>> print (pastaList) ['macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', ''] >>>
    and vice-versa.

    >>> lights = ["red", "green", "blue"] >>> type(lights) >>> # convert to tuple >>> lightsTuple = tuple(lights) >>> type(lightsTuple) >>> print lightsTuple ('red', 'green', 'blue') >>>
    Finally, you can iterate through a tuple in much the same way as a list - with the "for" loop.

    >>> pasta ('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni') >>> for x in pasta: ... print "I like", x ... I like macaroni I like spaghetti I like lasagne I like fettucine I like tagliatelle I like rigatoni >>>
    At this point, you're probably wondering why you need tuples when you already have lists to contend with. It's pretty simple: the built-in immutability of tuples provides an automatic defense against program code that attempts to change tuple elements, thereby ensuring the integrity of the data contained within this structure. As we progress through this tutorial, you'll see examples of where this might come in useful.{mospagebreak title=Keys To The Kingdom} One of the significant features of lists and tuples is that the values stored within them can only be accessed via a numerical index. The implication of this is obvious: if you need to access an element of the list or tuple, you need to first know its exact location in the structure. Since this can get complicated with large lists, Python offers you a simpler way to access list values, using a data structure known as a dictionary.

    Dictionaries are similar to lists and tuples, in that they allow you to group related elements together. However, where lists and tuples use an index to identify and locate specific elements or groups of elements, dictionaries use keywords ("keys") to accomplish the same task. In fact, Python dictionaries are the equivalent of Perl hashes or PHP associative arrays.

    Let's take a look at a simple example to demonstrate this:

    >>> characters = {"new hope":"Luke", "teacher":"Yoda", "bad guy":"Darth"} >>>
    Dictionaries are typically enclosed within curly braces, and each element within a dictionary consists of a "key" and a "value" associated with that key, separated from each other by a colon (:). Since every value in the dictionary is associated with a specific key, you can reference a specific value via its key.

    >>> characters["bad guy"] 'Darth' >>> characters["new hope"] 'Luke' >>>
    Defining a dictionary is not very difficult - simply assign key-value pairs (enclosed in curly braces) to a variable, as illustrated below:

    >>> characters = {"new hope":"Luke", "teacher":"Yoda", "bad guy":"Darth"} >>>
    You can also assign elements one at a time to an empty dictionary,

    >>> opposites = {} >>> opposites {} >>> opposites["white"] = "black" >>> opposites["yes"] = "no" >>> opposites["day"] = "night" >>> opposites {'day': 'night', 'white': 'black', 'yes': 'no'} >>>
    or add new elements to an existing one.

    >>> characters = {"new hope":"Luke", "teacher":"Yoda", "bad guy":"Darth"} >>> characters["princess"] = "Leia" >>> characters["worse guy"] = "The Emperor" >>> characters {'princess': 'Leia', 'teacher': 'Yoda', 'new hope': 'Luke', 'bad guy': 'Darth', 'worse guy': 'The Emperor'} >>>
    As you can see, the elements in a dictionary are not placed in a specific sequence, as with lists and tuples; new elements are assigned to random places within the dictionary space.

    It should be noted that keys and values in a dictionary need not be restricted to strings alone - numbers and tuples serve equally well as keys (which must be immutable),

    >>> mishmash = {"jack":"jill", 70:"sixty-nine plus one", (2,2):4, (1,2,3):(3,2,1)} >>> mishmash["jack"] 'jill' >>> mishmash[70] 'sixty-nine plus one' >>> mishmash[(2,2)] 4 >>> type(mishmash[(2,2)]) >>> mishmash[(1,2,3)] (3, 2, 1) >>> type(mishmash[(1,2,3)]) >>>
    while values could include strings, numbers, and even other dictionaries, lists or tuples (isn't it cool how Python allows you to nest one data structure within another?)

    >>> moremush = { ... "Friends":["Rachel", "Ross", "Joey", "Phoebe", "Monica", "Chandler"], ... "icecream":{"strawberry":"pink", "chocolate":"brown", "vanilla":"white"} ... } >>> # first value is list, second is nested dictionary >>> moremush {'icecream': {'chocolate': 'brown', 'vanilla': 'white', 'strawberry': 'pink'}, 'Friends': ['Rachel', 'Ross', 'Joey', 'Phoebe', 'Monica', 'Chandler']} >>> >>> moremush["icecream"] {'chocolate': 'brown', 'vanilla': 'white', 'strawberry': 'pink'} >>> type(moremush["icecream"]) >>> moremush["icecream"]["strawberry"] 'pink' >>> type(moremush["icecream"]["strawberry"]) >>> type(moremush["Friends"]) >>> moremush["Friends"][0] 'Rachel' >>>

    More Python Articles
    More By Vikram Vaswani, (c) Melonfire


     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway