0

I'm trying to write a script in python and I stumbled about this problem:

#read result file to list
def read_result():
    file_path = Path('../../results/result.txt')
    result = []
    with open(file_path) as file:
        for line in file:
            result.append(line.split())
    return(result)

# switch name and seq ID 
def rep_peak():
    replace_peak = read_result()
    header = replace_peak.pop(0)
    for res in replace_peak:
        name = res.pop(1)
        seq_ID = res.pop(3)
        res.insert(1, seq_ID)
        res.insert(4, name)

    replace_peak.insert(0, header)

    return(replace_peak)

# removes row if score < x 
def rm_row():
    row = rep_peak()
    header = row.pop(0)
    x = float(input("Enter x: "))
    print(len(row))
    i = 0
    for y in row:
        i = i + 1
        print(y)
        score = float(y.pop(3))
        if(score < x or score == x):
            row.remove(y)
        else: 
            print(score)

    print(i)


if __name__ == '__main__':
    read_result()
    rep_peak()
    rm_row()

The function rm_row has different lengths for the row list. When I print the length of row with len(row) it prints 221. When I count up i with a for loop and then print i I only get 111. Shouldn't those two numbers be the same? Please help me understand.

  • 1
    I have not read the code carefully, but don't remove an item in a `for` loop (at `row.remove(y)`). I believe that this is the culprit. – j1-lee Nov 24 '21 at 02:30
  • 1
    Exactly. Don't remove items from a list while you're iterating over it. Strange things happen. – John Gordon Nov 24 '21 at 02:35
  • Okay good to know thank you! How would you remove the item? I do have a list of lists and if a value is true I want to remove the sublist from the main list. – DarkDromeda Nov 24 '21 at 03:04
  • The usual way is to make a new list that has only the items you want to keep. – John Gordon Nov 24 '21 at 03:13

0 Answers0