python-3.xindexoutofrangeexception

Python 3.x : I'm out of range


I'm asking to have some help cause I believe I know why I'm out of range but I don't know out to solved it. Thanks you :D

#Import input.
from pathlib import Path
test = Path(r'C:\Users\Helphy\Desktop\Perso\GitHub\Advent_of_Code_2021\Day_3\Input.txt').read_text().split("\n")
#Defined some variable 
temp = []
finalnumtemp = []
finalnum = []
f_num = []
zero = 0
one = 0
for t in range(len(test)):
    for j in range(len(test)):
        temp = list(test[j])
        print(temp)
        finalnumtemp.append(temp[j])
        print(finalnumtemp)
     """for i in range(len(finalnumtemp)):
        if int(finalnumtemp[i]) == 0:
            zero += 1
        else:
            one += 1
    if zero > one:
        finalnum.append(0)
    else:
        finalnum.append(1)
    zero == 0
    one == 0
    finalnumtemp = []
print(finalnum)"""
    Input :
    00100
    11110
    10110
    10111
    10101
    01111
    00111
    11100
    10000
    11001
    00010
    01010
error: An exception has occurred: IndexError 
list index out of range
  File "C: \ Users \ Helphy \ Desktop \ Perso \ GitHub \ Advent_of_Code_2021 \ Day_3 \ Day_3.py", line 16, in <module>
    finalnumtemp.append (temp [j])

Solution

  • What to solve? What did you intend for the program to achieve?

    You have an error because...

    To select among the digits in temp, the index should be something of 0, 1, 2, 3, 4 (first, second, third, ... from the left) or -1, -2, -3, -4, -5 (first, second, third, ... from the right).

    To append the first of temp to finalnumtemp, fix

            finalnumtemp.append(temp[j])
    

    to

            finalnumtemp.append(temp[0])