[Tutor] assigning portions of list to another

Jeff Shannon jeff@ccvcorp.com
Tue, 17 Sep 2002 10:15:39 -0700


Joseph Paish wrote:

> i am trying to copy certain elements from a list into individual variables
> without writing one line of code for each assignment of value to variable.
> [...]
> >>> nbr1, nbr2, nbr3 = merged_rec[0, 3, 4]
> Traceback (innermost last):
>   File "<pyshell#15>", line 1, in ?
>     nbr1, nbr2, nbr3 = merged_rec[0, 3, 4]
> TypeError: sequence index must be integer

One thing that you might consider doing is using a class and class attributes,
instead of individual variables or list references.  For instance...

class record:
    def __init__(self, *args):
        argnumber = 1
        for arg in args:
            try:
                for item in arg:
                    setattr(self, 'nbr%d' % argnumber, item)
                    argnumber += 1
            except IndexError:
                setattr(self, 'nbr%d' % argnumber, arg)
                argnumber += 1

>>> rec1 = [1, 2, 3]
>>> rec2 = [4, 5, 6]
>>> merged = record(rec1, rec2)
>>> merged.nbr1
1
>>> merged.nbr5
5
>>>

This gives you the understandablity of named variables, while still allowing you
to keep track of everything as a group.  You could doubtless come up with some
attribute-naming scheme that's more useful than 'nbr1', 'nbr2', etc, that could
still be automatically generated.  If you wanted to get really fancy, you could
write a __setattr__() that would generate attribute names for you.

Or, if there is a specific set of fields in this record which will always appear
in the same order, you could give them more descriptive names.  This would still
involve one line for each field, but you'd only have to do so once, in the class
definition, and not each time that you want to use a record.

class record:
    def __init__(self, firstname, lastname, address, zip, phone):
        self.firstname = firstname
        self.lastname = lastname
        self.address = address
        self.zip = zip
        self.phone = phone

>>> r = record('john', 'smith', '123 main', '98104', '555-1212')
>>> r.zip
'98104'
>>>

Either of these approaches seems to me to be preferable to your plan of actually
using individual, unconnected variables, though admittedly this is to some degree
a matter of taste.

Jeff Shannon
Technician/Programmer
Credit International