Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increment index in for loop only if condition met

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading