Newbie Question: Obtain element from list of tuples

DevPlayer devplayer at gmail.com
Mon Dec 19 10:37:58 EST 2011


On Dec 19, 1:46 am, "Frank Millman" <fr... at chagford.com> wrote:
> "Steven D'Aprano" <steve+comp.lang.pyt... at pearwood.info> wrote in message
>
> news:4eeea8eb$0$11091$c3e8da3 at news.astraweb.com...
>
> > On Sun, 18 Dec 2011 18:35:47 -0800, alex23 wrote:
>
> >> Pre-namedtuple, I used to like using named slices for this:
>
> >>     cPID = slice(19)
> >>     pid = recs[cPID]
>
> > You know, that is an incredibly simple thing and yet it never dawned on
> > me before now. Thank you for sharing that.
>
> I also like it, but it does not work quite so simply for me.
>
> >>> row = tuple(range(20))
> >>> cPID = slice(15)
> >>> pid = row[cPID]
> >>> pid
>
> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
>
>
>
> This works -
>
>
>
> >>> row = tuple(range(20))
> >>> cPID = slice(15, 16)
> >>> pid, = row[cPID]  # note the trailing comma
> >>> pid
> 15
>
> Still nice, but not quite so elegant.
>
> Am I missing something?
>
> Frank Millman

if you're going to do:
> >>> cPID = slice(15, 16)
> >>> pid, = row[cPID]  # note the trailing comma

Why not just:
>>>row = tuple(range(20))
>>>cPID = 15 # a proposed constant
>>>pid = row[cPID]
>>>pid
15

It might be better for other's to debug if you use
>>> pid, _ = row[cPID]
as a little tiny comma like that is easy to miss in some text editors.
Not everyone has large LCD screens. Not that I like the "_" for this
purpose.

Personally I'd love to see the "_" used instead of "self" as a common
practice (useful when you use lots of "self...." on a line).




More information about the Python-list mailing list