please help shrink this each_with_index() implementation

Marco Nawijn nawijn at gmail.com
Tue Jan 5 15:20:58 EST 2010


On Jan 5, 8:58 pm, Phlip <phlip2... at gmail.com> wrote:
> Hypo Nt:
>
> def each_with_index(seq):
>     index = 0
>     result = []
>
>     for item in seq:
>       result.append([item, index])
>       index += 1
>
>     return result
>
> My Pythonic sequencing skills are obviously feeble. Can anything think
> of a way to write that in fewer lines?
>
> --
>   Phlip
>  http://c2.com/cgi/wiki?MoreliaViridis

You could use the build-in function enumerate inside a list
comprehension.

>>> seq = range(5)
>>> [ (i,s) for i,s in enumerate(seq) ]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

This will reduce the function to a one-liner.

Regards,

Marco



More information about the Python-list mailing list