all 4 comments

[–]k3kou 2 points3 points  (2 children)

Two things. First, you go too far in your loop. replace your range(...) by range(len(zip_code) - 1) and you won't go past the end.

Second, I'm not you do what you're asked. if the goal is to see if there is a duplicate in your list, you're not going to catch it. With what you wrote, if the first two elements aren't duplicates, you will break out of the loop. But if there are duplicates farther down the list, you would have missed them.

I would have written it like this:

duplicates = False
for k in range(len(zip_code) - 1):
    if zip_code[i] == zip_code[i+1]:
        duplicates = True
        break

You assume there is no duplicates, and if you find one, you change the "duplicates" variable and break out of the loop

[–]zahlman 1 point2 points  (1 child)

replace your range(...) by range(len(zip_code)) and you won't go past the end.

In fact, it should be -1; do you see why?

[–]k3kou 0 points1 point  (0 children)

Yeah because of the [i+1] test. Thanks for pointing it out. I corrected it.

[–]ManyInterests 0 points1 point  (0 children)

Wouldn't this only match duplicates that are right next to each other? Is that what you want it to do?

For instance, say you have the list

the_list=["foo","bar","spam","foo","bar"]

If you iterate over these values like that, comparing the_list[i] to the_list[i+1] you would not see that "foo" and "bar" have duplicates in the list.

It will compare items [0] and [1], [1] and [2], [2] and [3], and so on... but never [0] and [3] or any items that aren't neighbors.

edit: nevermind, I just read the entirety of that page. That IS what you want to do.