Skip to Content

We often want to use a for loop to search through a list for some value:

items_on_sale = ["blue_shirt", "striped_socks", "knit_dress", "red_headband", "dinosaur_onesie"] # we want to check if the item with ID "knit_dress" is on sale: for item in items_on_sale: if item == "knit_dress": print("Knit Dress is on sale!")

This code goes through each item in items_on_sale and checks for a match. After we find that "knit_dress" is in the list items_on_sale, we don’t need to go through the rest of the items_on_sale list. Since it’s only 5 elements long, iterating through the entire list is not a big deal in this case. But what if items_on_sale had 1000 items after "knit_dress"? What if it had 100,000 items after "knit_dress"?

You can stop a for loop from inside the loop by using break. When the program hits a break statement, control returns to the code outside of the for loop. For example:

items_on_sale = ["blue_shirt", "striped_socks", "knit_dress", "red_headband", "dinosaur_onesie"] print("Checking the sale list!") for item in items_on_sale: print(item) if item == "knit_dress": break print("End of search!")

This would produce the output:

Checking the sale list! blue_shirt striped_socks knit_dress End of search!

We didn’t need to check "red_headband" or "dinosaur_onesie" at all!



You have a list of dog breeds you can adopt, dog_breeds_available_for_adoption. Using a for loop, iterate through the dog_breeds_available_for_adoption list and print out each dog breed.


Inside your for loop, after you print each dog breed, check if it is equal to dog_breed_I_want. If so, print "They have the dog I want!"


Add a break statement when your loop has found dog_breed_I_want, so that the rest of the list does not need to be checked.

Folder Icon

Sign up to start coding

Already have an account?