if statement within for loop running time

663 Views Asked by At

I have a for loop iterating through a list with n elements, and within the list, I have an if statement, like so:

for item in list:
    if item == match:
        item = 'found'

My teacher says that this code is in ϴ(1). How is it not ϴ(n)? The loop is forced to iterate through n elements, why is the code in ϴ(1)? Is it perhaps an error on my teacher's part?

1

There are 1 best solutions below

5
Max von Hippel On

There are a few possibilities here.

  1. Your teacher is pulling the classic, and supremely slimy, "we know the size of the list" trick. This is a trick I have seen some smug individuals pull in which they claim that because n is known, n is a constant, ergo n is basically ~ 1. This is silly, bad logic, but it is something which some people fall back on sometimes.

  2. Your teacher is simply mistaken.

  3. Your teacher meant "best case" run-time, in which case the more precise statement would be Ω(1), if I remember my Greek correctly. But even this is wrong due to the lack of a break statement of any sort to exit the loop when the condition is met.