Sequence from every Nth Item of another Sequence

The phrase ‘every Nth item‘ may be off here, but it is close enough what I want to do (reduce a data set for charting purposes).

# data = sequence of data items
# nth = you want every nth element in the array
[data[index] for index in xrange(0, len(data), nth)]

for example:

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print [data[index] for index in xrange(0, len(data), 2)]   # [1, 3, 5, 7, 9]
print [data[index] for index in xrange(0, len(data), 3)]   # [1, 4, 7, 10]
print [data[index] for index in xrange(0, len(data), 4)]   # [1, 5, 9]
print [data[index] for index in xrange(0, len(data), 5)]   # [1, 6] 

This entry was posted in programming, Python. Bookmark the permalink.

12 Responses to Sequence from every Nth Item of another Sequence

  1. Andy D says:

    You could also use data[::n] to get every nth item. It is a lot shorter and clearer probably.

  2. Andrew Dalke says:

    Or, data[::2], data[::3], data[::4], etc.

  3. Robert Brewer says:

    I think you’ll find data[0::2] faster, in more ways than one.

  4. Jan Derksen says:

    Very nice. I will use this in the future. Thanks.

  5. ???????? says:

    >>> data= range(1, 11)

    ## A list from a list:
    ## data[::step]

    >>> data[::2]
    [1, 3, 5, 7, 9]
    >>> data[::3]
    [1, 4, 7, 10]

    ## An iterable from an iterable
    ## itertools.islice(data, 0, None, step)

    for item in itertools.islice(data, 0, None, 2):

  6. Ryan says:

    what’s wrong with `data[::n]`?

  7. Fabricio says:

    What about
    >>> print data[::n]
    where n is the desired step
    More generally:
    data[begin:excluded end:step]

    See http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange

  8. Y.Bonnemay says:

    data[::2] ?

  9. Lukas says:

    What about using itertools.islice? ;-)

  10. risingson says:

    Or you could use:
    data[::2]
    etc

  11. John Speno says:

    import itertools

    print list(itertools.islice(data, 0, None, 2)
    print list(itertools.islice(data, 0, None, 3)
    etc

  12. kpd says:

    Thanks everyone, I didn’t know about the other options – especially data[::2]. Just goes to show you that there is always something more to learn.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>