faqts : Computers : Programming : Languages : PHP : Common Problems : Files : Tips and Tricks

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

Entry

How do I select n items starting from position p in a list or string?

Jun 20th, 2002 08:19
Michael Chermside, Andrew Koenig, Eddie Corns, Martin v. Loewis


Python's slice notation is an extremely convenient way to select pieces
of a list, string, or any other sequence:
    part = x[a:b]
But that operates on start and just-past-end positions a and b. If you
have a start position, p and a length n, then you can use this simple idiom:
    part = x[p:p+n]
Well... you an ALMOST always use that. It works whenever p >= 0 (if n is
negative it will return an empty sequence). It works MOST of the time
when p < 0 (indexing backward from the end). But if p < 0 and n == -p,
then it reduces to
    part = x[p:0]
which is an empty slice, when what we wanted was all items from p on to
the end of the list. So there's a fancier idiom which will fix this
special case:
    part = x[p:p+n or sys.maxint]
It may not be worth using this more-difficult-to-read syntax if you
don't expect to support negative values of p. But if you DO, then it may
prove useful. It is certainly quicker than the alternative notation:
    part = x[p:][:n]
which would take about twice as long (for large lists) and consume much
more memory.