Login

Yet another list partitioning filter

Author:
AndrewIngram
Posted:
May 12, 2009
Language:
Python
Version:
1.0
Tags:
template filter partition
Score:
2 (after 2 ratings)

A simple template filter for breaking a list into sublists of a given length, you might use this on an ecommerce product grid where you want an arbitrary number of rows of fixed columns. Unlike the other partitioning filters I've seen, this doesn't try to distribute the rows evenly, instead it fills each row for moving onto the next.

This filter preserves the ordering of the input list.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.template import Library

register = Library()

@register.filter
def partition(input, n):
    """
    Break a list into sublists of length ``n``. That is, 
    ``partition(range(10), 4)`` gives::
    
        [[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10]]
    """
    try:
        n = int(n)
        input = list(input)
    except (ValueError, TypeError):
        return [input]
    return [input[i:i+n] for i in range(0, len(input), n)]

More like this

Comments

Please login first before commenting.