1

I have a larger list of approximately 250 elements. I need to group every 50 elements into a sub-list and iterate through each of the sub-lists.

For example:

largerList = [0, 1, ... ..., 268]

I want the sub lists to look like:

subLists = [[0, 1, ... ..., 49], [50, 51, ... ..., 99], ... ..., [250, 251, ... ..., 268]]

Then I will be able to iterate the sub lists and do something for each of them.

for ls in subLists:
  for i in ls:
    DO SOMETHING...
alextc
  • 3,206
  • 10
  • 63
  • 107

3 Answers3

7

You can use list comprehension to do this in a Pythonic manner. See below:

def group(original_list,n=50):

    return [original_list[x:x+n] for x in xrange(0,len(original_list),n)]

You actually don't need a function for this at all, but figured I'd show the functional way in case you wanted to vary the number of items in each sublist. This works just as well:

[original_list[x:x+50] for x in xrange(0,len(original_list),50)]
Moe Chughtai
  • 384
  • 2
  • 13
1

See grouper example in the itertools docs (not groupby) - that sounds like what you want:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
tschundler
  • 2,098
  • 1
  • 14
  • 15
  • Good call on grouper for very large lists. For what OP is describing, though, importing a library may be too heavy of a solution. – Moe Chughtai Jun 17 '16 at 02:25
0
count = len(largerList) / 50
i = 0
smallerList = []
while(i < count):
    smallerList.append(largerList[(i*50):(i*50)+50])
    i+= 1
hussamh10
  • 129
  • 9