Newbie Question: Obtain element from list of tuples

Roy Smith roy at panix.com
Sun Dec 18 15:04:13 EST 2011


In article <jclflh$u45$1 at news.albasani.net>,
 HoneyMonster <someone at someplace.invalid> wrote:

> Hi,
> 
> I'm just starting to learn Python, so please bear with me. I have in my 
> program an object (recs) which is a list of tuples (returned as such by a 
> database query).

Sounds like a standard database interface -- each tuple represents one 
row in the query result.  Very common.

> My question is doubtless a very easy one to answer: Say I want the ninth 
> element in the twentieth tuple put into variable PID, I can do this, 
> bearing in mind that numbering starts at zero:
> 
> tup = recs[19]
> PID = tup[8]

Sure, you could do:

PID = recs[19][8]

That's shorter, but it probably not better.  Presumably, the tuple 
elements represent columns in the database.  It would make the code 
easier to read if you unpacked the tuple into something with 
human-readable names:

col_1, col_2, col_3, ...... col_n = recs[19]

and then use the name for the column of interest.  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]

Of course, if you're going to do all that, you probably could have 
written a better query which returned just the column you were 
interested in.  Instead of "select * from foo", you could have done 
"select pid from foo" (assuming you're using some SQL-based database).

> Secondly, I am more than happy to read the fine manuals. If someone could 
> point me in the direction of one or two "for idiots" guides, that would 
> be greatly appreciated.

The on-line tutorial is pretty good.  
http://docs.python.org/tutorial/index.html



More information about the Python-list mailing list