Jhanlon Jhanlon - 4 months ago 19
Python Question

Python Error~ List index out of range

def getSublists(L,n):
List=L
sublists=[]
for i in range(len(L)-(n-1)):
ii=0
sub=[]
while ii<= n:
a=List[ii+i]
sub.append(a)
ii+=1
sublists.append(sub)

return sublists


I am trying to get all of the possible sublists of a list L and of sublist size n. I am getting an
IndexError: list index out of range
when I try to run my program. I've messed around with it to no avail and have read other relevant posts. Can someone help me out?

Answer

your while condition should be modified:

def getSublists(L,n):
    List=L
    sublists=[]
    for i in range(len(L)-(n-1)):
        print ['i: ', i]
        ii=0
        sub=[]
        while ii<= n-1:
            print ['ii: ', ii]
            a=List[ii+i]
            sub.append(a)
            ii+=1
        sublists.append(sub)

    return sublists

for a list of 10, you can now query all sub lists of 5

a=range(10)
b=getSublists(a,5)

out:
[[0, 1, 2, 3, 4],
 [1, 2, 3, 4, 5],
 [2, 3, 4, 5, 6],
 [3, 4, 5, 6, 7],
 [4, 5, 6, 7, 8],
 [5, 6, 7, 8, 9]