[Tutor] indexing a list

eryksun eryksun at gmail.com
Thu Oct 18 15:08:48 CEST 2012

```On Thu, Oct 18, 2012 at 8:01 AM, Spyros Charonis <s.charonis at gmail.com> wrote:
>
> x = 21   # WINDOW LENGTH
>
> In : SEQ[0:x]
> Out: 'MKAAVLTLAVLFLTGSQARHF'
>
> In : SEQ[x:2*x]
> Out: 'WQQDEPPQSPWDRVKDLATVY'
>
> In : SEQ[2*x:3*x]
> Out: 'VDVLKDSGRDYVSQFEGSALG'
>
> How could I write a function to automate this so that it does this from
> SEQ throughout the entire sequence, i.e. until len(SEQ)?

In your examples, the lower slice limit is 0x, 1x, 2x, and so on. The
upper limit is 1x, 2x, 3x, and so on. That should scream that you need
a counter, or range/xrange. The lower limit of the last slice should
be less than len(SEQ), such that there's at least 1 item in the last
slice. So, in terms of range, the start value is 0, and the stop value
is len(SEQ). To make things even simpler, range takes an optional step
size. This gives you the 0x, 1x, 2x, etc for the start index of each
slice. The upper bound is then i+x (corresponding to 1x, 2x, 3x, etc).
For example:

>>> seq = 'MKAAVLTLAVLFLTGSQARHFWQQDEPPQSPWDRVKDLATVYVDVLK'
>>> x = 21
>>> for i in range(0, len(seq), x):
...     print(seq[i:i+x])
...
MKAAVLTLAVLFLTGSQARHF
WQQDEPPQSPWDRVKDLATVY
VDVLK

If you're using Python 2.x, use xrange instead of range, and "print"
is a statement instead of a function.

You can also use a generator expression to create a one-time iterable
object that can be used in another generator, a for loop, a
comprehension, or as the argument of a function that expects an
iterable, such as the list() constructor:

>>> chunks = (seq[i:i+x] for i in range(0, len(seq), x))
>>> list(chunks)
['MKAAVLTLAVLFLTGSQARHF', 'WQQDEPPQSPWDRVKDLATVY', 'VDVLK']
```