You can use zip
function :
>>> l=(0,1,2,3,4,5)
>>> zip(l,l[1:],l[2:])
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
The following benchmark shows that using zip
is faster than islice
or a simple list comprehension :
:~$ python -m timeit "l=(0,1,2,3,4,5);from itertools import islice;[list(islice(l, i, i + 3)) for i in range(len(l) - 3 + 1)]"
100000 loops, best of 3: 4.47 usec per loop
:~$ python -m timeit "l=(0,1,2,3,4,5);[l[i: i + 3] for i in range(len(l) - 3 + 1)]"
1000000 loops, best of 3: 0.632 usec per loop
:~$ python -m timeit "l=(0,1,2,3,4,5);zip(l,l[1:],l[2:])"
1000000 loops, best of 3: 0.447 usec per loop
Also as says in comment for long lists and also for large slices you can use izip
and islice
functions from itertools
module :
zip_longest(*(islice(l, i) for i in range(n))) # in python 3
izip(*(islice(l, i) for i in xrange(n))) # in python 2