Why does list have no 'get' method?

pruebauno at latinmail.com pruebauno at latinmail.com
Thu Feb 7 14:51:06 EST 2008


On Feb 7, 12:15 pm, prueba... at latinmail.com wrote:
> On Feb 7, 11:01 am, "Denis Bilenko" <denis.bile... at gmail.com> wrote:
>
>
>
> > Steve Holden wrote:
> > > These versions differ with respect to treatment of blank lines, which
> > > indicates  how easy it is to go astray in this kind of semantic
> > > optimization. Your example simply wouldn't work (though you could patch
> > > it up using "if line is None". (despite the use of short-circuiting
> > > predicates).
> > > > both examples show reduction by 3 lines.
>
> > > Perhaps so, but you have to realise that Python has never valued code
> > > compactness over clarity.
> > > I'm not sure that your democratic wish to ensure fairness to sequences
> > > will garner much support, interesting though it is in an academic sense.
>
> > Thank you for the patch. My incentives are not academic though.
>
> > I convinced that this
>
> >     line = self._buffer.get(self._bufindex)
> >     if line is None:
> >         self._bufindex += 1
> >         self._lineno += 1
> >         self._filelineno += 1
> >         return line
> >     line = self.readline()
>
> > is more clear than
>
> >     try:
> >         line = self._buffer[self._bufindex]
> >     except IndexError:
> >         pass
> >     else:
> >         self._bufindex += 1
> >         self._lineno += 1
> >         self._filelineno += 1
> >         return line
> >     line = self.readline()
>
> > I mentioned 3 lines reduction just because it is
> > objective, while 'more clear' is subjective.
>
> > Code snippets are again not equivalent, e.g. in the
> > case when self._buffer[self._bufindex] exists and is
> > equal to None. Although the author could probably
> > make a guarantee that is never the case.
>
> This has been a pet peeve of mine too. So you are not completely
> crazy:
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269484
>
> There is a discussion about precisely this by Alex Martelli in the
> printed version of the Python cookbook (2nd edition). I don't share
> the opinion but I am not going to fight the core Python developers
> over it. I don't think it is worth the effort. Python is so smooth
> already, there has to be some excuse to add some cute hack to your
> program once in a while :-).
>
> dict(enumerate(lst)).get(i,default) for example although not very
> efficient, looks cute. I think I like it better than my own solution.

Actually to clarify, I think this is more useful for tuples (or tuple
like structures) than lists per se. On homogeneous lists I usually
iterate. It is on heterogeneous that I want to extract specific fields
that might be optional.



More information about the Python-list mailing list