Kronyklos Kronyklos - 1 year ago 64
Python Question

If statement acting like while statement python3

For some reason, this code:

def display_jan_appointments():
for item in appointment_dates:
if item[0:2] == "01" and item[3:5] == "01" and not adding:
pygame.draw.ellipse(screen, BLUE, [915, 275, 20, 20])
jan1 = True
global jan1

Infinitely adds the index of the item to the jan_1_index list. I'm not sure why, as the if statement should only be iterated through once, because it's not a while statement. Is it do with the code being in a function, or is it something else?

Edit: When I print the list out, it outputs:

[0, 0]
[0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0]

and so on.

Double edit: I produced a small section of code with everything necessary.

appointment_dates = ["01/01", "01/01"]
jan_1_index = []
adding = False
for item in appointment_dates:
if item[0:2] == "01" and item[3:5] == "01" and not adding:

This code, however, outputs the list like it is supposed to, just [0, 0]. Why is this?

Answer Source

Two issues with the code - list.index will always return the index of the first match - so effectively, you'll get repeated indices. The other issue (which is hard to tell from your code) is that likely something is mutating appointment_dates...

The Pythonic way to do this is via using a list-comp, eg:

jan_1_index = [
    idx for idx, item in enumerate(appointment_dates) 
    if item[:2] == '01' and item[3:5] == '01' # and not adding
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download