# IndexError: list index out of range

Peter Otten __peter__ at web.de
Tue Dec 13 04:15:03 EST 2016

Elnaz wrote:

> hi
> i am begginer in python. I have written a code and given this error:
> IndexError: list index out of range
>
> In my program, I have h=32 bits input. i divide this 32 bits to 4*8 block
> and every 8-block is n. so n=0:7;(h=int(n/4)) I want to rotate 0 to 7 bits
> for 2 bits: 0,1,2,3,4,5,6,7--->2,3,4,5,6,7 Iwrite this code:
> def rottwo(self, X, n, r):
>         assert r >= 1
>         temp = [None]*n
>         for i in range(n-r) :
>             temp[i] = X[i+r]
>         for i in range(n-r,n) :
>             temp[i] = X[i-n+r]
>         return temp
> this function work correctly. but I also want to rotate 24 to 31 bits for
> 5 bits: 24,25,26,27,28,29,30,31-->29,30,31,24,25,26,27,28
>
> when I write this code:
> def rotfive(self, X, n, r):
>        assert r >= 1
>        temp = [None]*n
>        for i in range(n-r) :
>             temp[i+24] = X[i+3*n+r]
>        for i in range(n-r,n) :
>             temp[i+24] = X[i+2*n+r]
>        return temp
> beacase temp is of size n I cannot access index 3*n+i. index on the list
> temp should be less than equal to n-1 . I son't know how I must correct
> this!!!!!!!! Is there any one to help me?

I think you are making this harder than necessary. Python slices make
accessing parts of a list quite elegant:

>>> items
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> items[2:5]
[20, 30, 40]
>>> items[3:]
[30, 40, 50, 60, 70, 80, 90]

You can use this to implement a function that creates a rotated list with an
arbitrary offset:

>>> def rot(items, offset):
...     return items[offset:] + items[:offset]
...
>>> rot(items, 2)
[20, 30, 40, 50, 60, 70, 80, 90, 0, 10]
>>> rot(items, 7)
[70, 80, 90, 0, 10, 20, 30, 40, 50, 60]
>>> rot(items, -2)
[80, 90, 0, 10, 20, 30, 40, 50, 60, 70]

To rotate part of a list extract that part using slice notation, rotate it
and write it back:

>>> def rot_part(items, offset, start, stop):
...     items = list(items)
...     items[start:stop] = rot(items[start:stop], offset)
...     return items
...
>>> rot_part(range(32), 5, 24, 32)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 29, 30, 31, 24, 25, 26, 27, 28]

If you pass a list as the first argument

items = list(items)

makes of copy of the list, but it will also convert an arbitrary iterable to
a list. That's why I can pass the range object.