Question

I'm trying to add items to 2D array "groups". I'm getting error. I know why, but I don't know how to solve it. I tried groups[1].add but it did not work. The array groups[1] doesnt exists when I am trying to append. Is there a way, how to make this array only when it is necessary (when trying to append or add or insert)?

def sortResults(results,pattern):
    ordered=results
    ordered.sort()
    groups= [[]]
    for r in results:
        print r
        tuple=evaluate(pattern,r)
        print(tuple)
        if tuple[0]==1:
            groups[0].append(r)
        elif tuple[0]==2:
            groups[1].append(r)
    for group in groups:
        print(group)
        for item in group:
            if item != 0:
                ordered.remove(item)
                ordered.append(item)


    return ordered

I'm getting this error:

groups[1].append(r)
IndexError: list index out of range

Thanks in advance!

Was it helpful?

Solution

Why not use:

groups = [[], []]

instead if you are going to append to two groups? Then you won't run into that problem.

You can always remove it again if it remains empty, or you can use exception handling:

elif tuple[0]==2:
    try:
        groups[1].append(r)
    except IndexError:
        groups.append([r])

as the list missing is only a problem once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top