a better way to invert a list?

scattered tooscattered at gmail.com
Wed Apr 6 05:48:22 EDT 2011


On Apr 6, 4:48 am, Glazner <yoavglaz... at gmail.com> wrote:
> > > def invert(p):
> > >     inverse = [None] * len(p)
> > >     for (i, j) in enumerate(p):
> > >         inverse[j] = i
> > >     return inverse
>
> > Elegant. This seems like the best solution, although it isn't as much
> > fun to write as a "one-liner". Thanks
> >>> invert([1, 2, 3, 1])
>
> [None, 3, 1, 2] #blah

I'm not sure if your post was meant to be serious, but if it was note
that [1,2,3,1] isn't a list which represents a permutation of
0,1,...,n-1 (where n is the length of the list). Ian Kelly's code
works correctly for input of the specified form.




More information about the Python-list mailing list