Home arrow Python arrow Page 4 - Python 101 (part 4): Feeding The Snake

Unbreakable - Python

Luke Skywalker has the Force. Python programmers havedictionaries and tuples. What's the connection? Read on to find out...

TABLE OF CONTENTS:
  1. Python 101 (part 4): Feeding The Snake
  2. Running The Lights
  3. Strange Food
  4. Unbreakable
  5. Looking Up The Dictionary
  6. Of Keys And Locks
By: Vikram Vaswani, (c) Melonfire
Rating: starstarstarstarstar / 8
June 25, 2001

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: