Newbie Question: Obtain element from list of tuples

alex23 wuwei23 at gmail.com
Sun Dec 18 21:35:47 EST 2011


Roy Smith <r... at panix.com> wrote:
> A common convention
> is that when you're unpacking a tuple (or a list, I suppose) and are
> only interested in some of the elements, you unpack the others into "_".
> Thus:
>
> _, _, _, _, pid, _, _, _ = recs[19]

Pre-namedtuple, I used to like using named slices for this:

    cPID = slice(19)
    pid = recs[cPID]

    cHostPort = slice(99,100)
    host, port = recs[cHostPort]

etc.

The suggestions of having your query return a dictionary where
possible are the most ideal, but if it's not possible you can always
wrap the result tuple in a namedtuple:

    from collections import namedtuple

    Staff = namedtuple('Staff',
['firstname','lastname','age','position'])

    sql_result = ('John', 'Example', '30', 'Dummy')
    staff_record = Staff(sql_result)

    print staff_record.firstname, staff_record.age



More information about the Python-list mailing list