Photo by [Chris Ried]( on

Python for loops have an else clause

Something that is not common knowledge is the fact that Python for loop can have an else clause. An else clause is executed when a for loop ends normally without break being called. Internally, Python will trigger a StopIteration when this happens. def check(target, iterable): for element in iterable: if element == target: print("Jup, target is in container.") break else: print("Seems like target is not in container.") check("s", "a string") # >>> Jup, target is in container....

September 22, 2022 ยท Alexander Neumann