Increment index in for loop only if condition met

Question:

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’

Asked By: Kris West

||

Answers:

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:

numTasksIncomplete = 0
for index, item in enumerate(read_list, 1):
    item = item.rstrip('n')
    if item[0] == '❌':
        print(f'{index}. {item}')
        numTasksIncomplete += 1
Answered By: Jeffrey Ram

You need to understand the purpose of variable index you are trying to increment.

Currently, index and item and assigned new values every time the loop iterates over read_list. index and task in the for loop with enumerate basically resolves to getting the index and value from read_list one by one.

You are trying to increase the same variable index inside if condition.

Even if you increment it, next time the loop runs, it will overwrite the value.

If you are trying to count the number of tasks that are incomplete, you can use a new variable and name it different that one you are using in the for loop.

Try this :

incomplete_count = 0
for index, item in enumerate(read_list, 1):
    item = item.rstrip('n')
    if item[0] == '❌':
        print(f'{index}. {item}')
        incomplete_count += 1
Answered By: Prashant Kumar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.