Slice Notation?

Alex Martelli aleaxit at yahoo.com
Sun Oct 22 05:52:11 EDT 2000


"Wynand van Dyk" <wynand at mindspring.co.za> wrote in message
news:39F2CF69.372971ED at mindspring.co.za...
> Hi,
>
> I am pretty new to python and I keep seeing ppl referring to "slice
> notation"
> which include a colon in square brackets somewhere in your code.
>
> I would like to know:
>
> 1) What exactly does it do?

It returns a "slice" of a sequence -- some compact part of it.
For example:

>>> foo = "hello world"
>>> foo[3:7]
'lo w'
>>> foo[:-2]
'hello wor'
>>> foo[5:]
' world'

When applied to _modifiable_ sequences (not strings or
tuples, but for example lists) it also lets you *change*
such a portion of a sequence, e.g.:

>>> foo = list("hello world")
>>> foo[3:7] = list("p the W")
>>> ''.join(foo)
'help the World'
>>>


> 2) What is it usefull for?

Lots of things.  Every time you need to refer to "all
but the first" or "all but the last" or "all but the first
and last" of a sequence, for example, slices are just
what you want:
    foo[1:]    # all but the first
    foo[:-1]    # all but the last
    foo[1:-1]    # all but the first and last


> 3) How would I use it in a program ie: example usage

See above for simple examples.  Here's a simple
real case: given a sequence of observations (data
points, typically a list) return the sequence of
'moving averages' with window 5 and step 2:

def average(seq):
    total = 0.0
    for x in seq: total += x
    return total/len(seq)

def movavg(seq,window=5,step=2):
    result = []
    for i in range(0,len(seq),step):
        result.append(average(seq[i:i+window]))
    return result

It can be done in other ways, of course!, but this
is simple and readable.


Alex






More information about the Python-list mailing list