So I'm fairly new to Python, and I'm having difficulty understanding why this code wont compile. The point is to go line by line through the file, find the difference between the highest and lowest int, and sum the difference for all lines. It seems to me like the int casting is causing an issue; without it Python seems to accept that the first index of each list is a string, but if I try and cast that string as an int then that index apparently doesn't exist.
sum_count = 0
with open('C:\\...\\input_day_two.txt') as file:
for line in file:
line_list = line.split()
list_copy = line_list.copy()
line_count = len(list_copy)
smallest = int(list_copy[0])
largest = int(list_copy[0])
for index in range (line_count):
if int(list_copy[index]) < smallest:
smallest = int(list_copy[index])
if int(list_copy[index]) > largest:
largest = int(list_copy[index])
difference = largest - smallest
sum_count += difference
print(sum_count)
I thought initially that there may be an issue with trying to access the list indices outside of the for loop, but Python will recognize and print out every index of the list outside of the loop. I have to imagine the error has something to do with int parsing, but I can't see why.
Edit: This is the error that's being thrown
Traceback (most recent call last):
File "C:/.../adventcode_daytwo.py", line 7, in <module>
smallest = int(list_copy[0])
IndexError: list index out of range