Suppose I have a list [a,b,c,d,e], I want to create a list of tuples [(a,b,c),(b,c,d),(c,d,e)]. Is it possible without using array indices as my loop variable? What is the best way of doing this?
Asked
Active
Viewed 168 times
3 Answers
1
zip(li, li[1:],li[2:])
This zips together the elements. Each iteration corresponds to li[i], li[i+1], li[i+2], hence solving the original problem.

Karthick
- 4,456
- 7
- 28
- 34
-
This copies the list over and over, and doesn't work for an iterator / generator rather than list. It also creates all the windows immediately on Python 2, consuming width of window * length of list memory. – agf Sep 10 '11 at 14:52
0
Not sure this satisfies your constraints, but it should do it.
the_list = [1,2,3,4,5,6,7]
tuple_size = 3
tuple_list = [tuple(the_list[i-tuple_size:i]) for i in range(tuple_size, len(the_list))]

Alec Munro
- 223
- 1
- 6
0
I keep this handy function around for when I want to do this.
import itertools
def nwise(it, n, wrapping=False):
# nwise('ABCD', 2) --> AB BC CD
# nwise('ABCDEF', 3) --> ABC BCD CDE DEF
# nwise('ABCD', 2, wrapping=True) --> AB BC CD DA
# nwise('ABCD', 3, wrapping=True) --> ABC BCD CDA DAB
copies = itertools.tee(it, n)
columns = []
for index, copy in enumerate(copies):
front = list(itertools.islice(copy, 0, index))
if wrapping:
columns.append(itertools.chain(copy, front))
else:
columns.append(copy)
return itertools.izip(*columns)

Mike Graham
- 73,987
- 14
- 101
- 130