[CentralOH] Handy function to decimate a list of numbers (get every Nth item)

Bryan Harris harrisbw at notes.udayton.edu
Wed Mar 18 21:48:50 CET 2009

Hey all, I came up with this little snippet to get every Nth line in a list.    
Google didn't turn anything up in the first few pages.  Does anybody know a 
better way?  This seems like the kind of thing python would be able to do 
automatically using the % (modulo) symbol or something.

def decimate(array,points):
    if type(points) != type(1):  #line 1.5 doesn't mean anything!
        raise Error, "number of points should be an integer"
    if len(array)/2<=points:  #Not worth doing for an array this small
        return array

    #get the line numbers rather than stepping through the entire list
    line_numbers = range(0,len(array),interval)
    for each in line_numbers:
        new_array=new_array + [array[each]]

Bryan Harris
Research Engineer
Structures and Materials Evaluation Group
harrisbw at notes.udayton.edu
(937) 229-5561

More information about the CentralOH mailing list