For example, I have simple list like this:
l = [1,2,3,4,5,6,7,8,9]
I want to iterate over it in groups of 3 elements:
1,2,3
4,5,6
7,8,9
What is simplest way to do it?
For example, I have simple list like this:
l = [1,2,3,4,5,6,7,8,9]
I want to iterate over it in groups of 3 elements:
1,2,3
4,5,6
7,8,9
What is simplest way to do it?
Tricky, but well-known way (from itertools
grouper recipe):
>>> zip(*[iter(l)] * 3))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
It can be written as
>>> it = iter(l)
>>> zip(it, it, it)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Full explanation here: How does zip(*[iter(s)]*n) work in Python?
You can do it as:
l = [1,2,3,4,5,6,7,8,9]
result = [l[i:i+3] for i in range(0,len(l),3)]
>>> print result
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> for i in result:
... print(i)
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
You could write simple generator
def group_gen(lst, n):
for i in range(0,len(lst), n):
yield l[i:i+n]
for a,b,c in group_gen(l, 3):
print(a,b,c)
Results in:
1 2 3
4 5 6
7 8 9