Nathan Danzmann
Nathan Danzmann

Reputation: 105

Python "List assignment index out of range"

I am a novice student in Python (and programming in general).

I am supposed to make a python program that opens two files with random numbers in them and creates a new file with the numbers ordered from lowest to highest.

So I made this code that iterates using two for loops through all the numbers, searching for the lowest, very basic stuff, than stores the number and its position, appends to a Lmix list that will be saved on the final file and stores the numbers position to delete it from that list so it won't be found again.

The variables are in Portuguese, but I translated them in the comments, the rest are self-explanatory.

arq1 = open("nums1.txt","r")
arq2 = open("nums2.txt","r")

arqmix = open("numsord.txt","w")

L1 = arq1.readlines()
L2 = arq2.readlines()
Lmix = []

L1 = list(map(int,L1)) # converts lists into int
L2 = list(map(int,L2))

cont = 0

menor = L1[0]  # "Menor" is the variable that stores the lowest number it finds
menorpos = 0   # "Menorpos" is the position of that variable in the list, so it can delete later
listdec = 0    # "listdec" just stores which list the number was from to delete.

while cont != (len(L1)+len(L2)):   

# while loops that finds the lowest number, stores the number and position, appends to the Lmix and deletes from the list so it won't be found on next   iteration

    n = 0
    for n,x in enumarate(L1):
        m = 0
        for m,y in enumarate(L2):
            if x<menor:
                menor = x
                menorpos = n
                listdec = 0
            elif y<menor:
                menor = y
                menorpos = m
                listdec = 1
            m += 1
        n += 1

    Lmix.append(menor)
    if listdec == 0:
        del L1[menorpos]
    elif listdec == 1:
        del L2[menorpos]
    cont += 1

for x in Lmix:
    arqmix.write("%d\n"%x)

arq1.close()
arq2.close()
arqmix.close()

But everytime I run it, this error appears:

Traceback (most recent call last): File "C:/Users/Danzmann-Notebook/PycharmProjects/untitled/aula18.py", line 41, in del L2[menorpos] IndexError: list assignment index out of range

I know what it means but I just can't understand why it happens, and how can I solve it.

Any help would be appreciated.

Thanks in advance, sorry for any grammar error, english is not my native language.

Upvotes: 0

Views: 439

Answers (2)

Nishant Srivastava
Nishant Srivastava

Reputation: 379

You dont need to increment m and n explicitly. That is already being done for you. This may be causing the index out of range.

    m += 1
n += 1

Upvotes: -1

Hugh Bothwell
Hugh Bothwell

Reputation: 56694

To debug this, I added two print statements in the while loop - this is what I saw:

Cont: 0  L1 [9, 2, 6, 4, 7]  L2 [3, 15, 5, 8, 12]  Lmix []
  Found menor 2 menorpos 1 listdec 0

Cont: 1  L1 [9, 6, 4, 7]  L2 [3, 15, 5, 8, 12]  Lmix [2]
  Found menor 2 menorpos 1 listdec 0

Cont: 2  L1 [9, 4, 7]  L2 [3, 15, 5, 8, 12]  Lmix [2, 2]
  Found menor 2 menorpos 1 listdec 0

Cont: 3  L1 [9, 7]  L2 [3, 15, 5, 8, 12]  Lmix [2, 2, 2]
  Found menor 2 menorpos 1 listdec 0

Cont: 4  L1 [9]  L2 [3, 15, 5, 8, 12]  Lmix [2, 2, 2, 2]
  Found menor 2 menorpos 1 listdec 0

Traceback (most recent call last):
  File "<pyshell#30>", line 29, in <module>
    del L1[menorpos]
IndexError: list assignment index out of range

The first time through the loop, it works correctly - it finds the lowest item in either list, assigns the right values to menor, menorpos, and listdec, and removes that value.

The second time through the loop, it fails because menor already was the lowest value - it does not find a lower value, so it never updates the values for menor, menorpos, and listdec. It uses the previous values (which are now incorrect).

It repeats using the wrong values until the list it is deleting from is too short; then it throws an error.


The problem can be solved much more simply:

def loadnums(filename):
    with open(filename) as inf:
        nums = [int(line) for line in inf]
    return nums

nums = loadnums("num1.txt") + loadnums("num2.txt")
nums.sort()

with open("numsord.txt", "w") as outf:
    outf.write("\n".join(str(num) for num in nums))

Upvotes: 0

Related Questions