If you're happy to use numpy...
list(numpy.abs(numpy.ediff1d(l, to_end=l[0]-l[-1])))
This scales well with longer l
. Not converting to or from a list will speed things up quite a bit (very often a numpy array can be used in place of a list anyway).
Or you can construct it youself using numpy.roll
:
list(numpy.abs(l - numpy.roll(l, -1)))
A few timings:
In [37]: l = list(numpy.random.randn(1000))
In [38]: timeit [abs(v - l[(i+1)%len(l)]) for i, v in enumerate(l)]
1000 loops, best of 3: 936 us per loop
In [39]: timeit list(numpy.abs(numpy.ediff1d(l, to_end=l[0]-l[-1])))
1000 loops, best of 3: 367 us per loop
In [40]: _l = numpy.array(l)
In [41]: timeit numpy.abs(numpy.ediff1d(_l, to_end=l[0]-l[-1]))
10000 loops, best of 3: 48.9 us per loop
In [42]: timeit _l = numpy.array(l); list(numpy.abs(_l - numpy.roll(_l, -1)))
1000 loops, best of 3: 350 us per loop
In [43]: timeit numpy.abs(_l - numpy.roll(_l, -1))
10000 loops, best of 3: 32.2 us per loop
If raw speed is your thing, quicker still, but not so neat, you can use sliced arrays directly:
In [78]: timeit a = numpy.empty(_l.shape, _l.dtype); a[:-1] = _l[:-1] - _l[1:]; a[-1] = _l[-1] - _l[0]; a = numpy.abs(a)
10000 loops, best of 3: 20.5 us per loop