[Tutor] Do tuples replace structures?

Terry Carroll carroll at tjc.com
Mon Jan 12 14:36:40 EST 2004


On Mon, 12 Jan 2004, Todd G. Gardner wrote:

> Do tuples allow one to form data structures like those formed by structures
> in 'c' or are there better ways to form structures in python?

You can do structures in tuples (although lists are probably a better way, 
being mutable).  If you do that, you have to remember what element number 
corresponds to what data, e.g.:

 record = ["Jim", "Smith", 22, 130]

It's up to you to remember that record[0] is first name, record[1] is last 
name, etc.

A dictionary makes this a little easier:

 record = {
   "fname":"Jim",
   "lname":"Smith",
   "age":22,
   "weight":130
   }

Then you can refer to, for example, record["age"] and pull out the age.

I prefer to use classes, though for just about anything where I need a 
structure:

>>> class person:
...   def __init__(self,fname,lname,age,height):
...     self.fname = fname
...     self.lname = lname
...     self.age = age
...     self.height = height
...
>>> record = person("Jim", "Smith", 22, 130)
>>> record.fname
'Jim'

-- 
Terry Carroll
Santa Clara, CA
carroll at tjc.com 




More information about the Tutor mailing list