I’m currently learning Python and run into a bit of a snag. I’m building a simple to-do list, and I’ve built it out to display a list only if the first character is a ❌. This works, but when an item is marked complete (with a ✅), it still counts increments the index on the code below.
I assumed that index += 1 inside an if statement would only increment the index if the condition is met – is this not the case?
def read_list():
read_list = open("todo.txt","r", encoding='utf-8')
for index, item in enumerate(read_list, 1):
item = item.rstrip('\n')
if item[0] == '❌':
print(f'{index}. {item}')
index += 1
The current output of this is:
1. ❌ TASK 1
3. ❌ TASK 2
This is because the second item on the list is ‘✅ TASK 3’
>Solution :
for index, item in ... already increments index. On your first loop, you are printing (current index 1) then adding (current index 1) + 1 which is 2 then increments + 1 with for loop. So in your second loop, it prints 3.
Create a separate variable outside of the for loop:
numTasks = 0
for index, item in enumerate(read_list, 1):
item = item.rstrip('\n')
if item[0] == '❌':
print(f'{index}. {item}')
numTasks += 1