What is the Pythonic way of getting elements from the list in groups? I.e., I want the first 10 elements of a list, then the next 10 elements, then the next 10 elements, etc.
Asked
Active
Viewed 471 times
1
-
3Something like this? http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks or http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python Look in here, lots of good stuff http://docs.python.org/2/library/itertools.html#recipes – Nov 21 '13 at 04:31
2 Answers
5
You can use a generator function like this
def getElements(data, n):
for i in xrange(0, len(data), n):
yield data[i:i+n]
And then iterate over the generator like this
data = range(100)
for i in getElements(data, 20):
print i
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

thefourtheye
- 233,700
- 52
- 457
- 497
-
1What's the purpose of `inner`? Couldn't you just take the body of `inner` and make it the body of `getElements`? – user2357112 Nov 21 '13 at 04:40
-
@user2357112 Oh yes. Thats not necessary at all. Removed that. Thank you :) – thefourtheye Nov 21 '13 at 04:42
2
>>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
>>> b = [ a[i:i+10] for i in range(0,len(a),10) ]
>>> b
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23]]
Hope it is pythonic enough. To change chunks (say for size = chunk_size
, you'd have to change a[i:i+chunk_size]
and change range to range(0,len(a),chunk_size)

slider
- 12,810
- 1
- 26
- 42
-
2`[x for x in a[i:i+10]]` is a strangely verbose way to say `a[i:i+10]` or `list(a[i:i+10])`. – user2357112 Nov 21 '13 at 04:39
-
@user2357112 LOOOL! That's right. I just started learning list comprehensions. Unfortunately it showed. – slider Nov 21 '13 at 04:44