0

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])
                jan_1_index.append(appointment_dates.index(item))
                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, 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:
        jan_1_index.append(appointment_dates.index(item))               
        print(jan_1_index)

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

12
  • 3
    Can you check that jan_1_index points not to the same object as appointment_dates? Commented Jul 10, 2016 at 4:05
  • @DAXaholic They're two separate arrays. Commented Jul 10, 2016 at 4:11
  • How have you determined that it's adding "infinitely"? If the program locks up, how do you know that particular list is becoming infinitely big? No, if statements don't suddenly become infinite loops because they're inside functions, that would be unusable... Commented Jul 10, 2016 at 4:12
  • @TessellatingHeckler The program doesn't lock up, and I've got the list being printed out which, every line printed out, it increases by one. Commented Jul 10, 2016 at 4:12
  • If it's not locking up, then the if statement cannot be acting like a while statement, right? Otherwise it would never leave there, and would lock up... can you post more code? Are you calling display_jan_appointments too many times? Commented Jul 10, 2016 at 4:14

1 Answer 1

2

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
]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.