Idiosyncratic python

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Sep 24 15:09:28 CEST 2015


On 24/09/2015 13:50, paul.hermeneutic at gmail.com wrote:
>  > A lot of our in base weird python comes from heavily C-wired people:
>  >
>  > The classic
>  > for i in range(len(alist)):
>  >   print alist[i]
>  >
>  > with its twin brother
>  >
>  > i=0
>  > while i < len(alist):
>  >   print alist[i]
>  >   i += 1
>  >
>  > And the even more annoying
>  >
>  > result = Result()
>  > getResult(result)
>  >
>  > JM
>
> Please follow up with good ways to write these. I hear that creating one
> really good way is a Python maxim.
>

for item in alist:
     print(item)

If you *think* you need the index:-

for i, item in enumerate(alist):
     print(i, item)
`i` defaults to 0, but there is a `start` keyword argument that lets you 
set it to anything you like.

Better IMHO is to see what the itertools module[1] offers, either 
directly or through recipes.  The latter are available on pypi as 
more-itertools[2].

[1] https://docs.python.org/3/library/itertools.html
[2] https://pypi.python.org/pypi/more-itertools/

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Python-list mailing list