Glossary

For Loop

The for loop in Python iterates over the items of any iterable object — lists, tuples, strings, dictionaries, sets, files, ranges, generators, and any object that implements __iter__(). The syntax is for item in iterable: followed by an indented block. Unlike C-style for (i = 0; i < n; i++) loops, Python's for is a "for-each" loop that abstracts away index management.

The range() function generates a sequence of integers for index-based iteration: for i in range(10): loops from 0 to 9. enumerate(iterable) yields (index, item) pairs, and zip(a, b) pairs corresponding elements from multiple iterables. These built-in functions make the vast majority of loops clean and index-free.

Python's for loop has an optional else clause that executes when the loop completes without hitting a break. This is unusual among programming languages and is most useful for search loops: the else block runs if the item was not found. For transforming iterables, comprehensions and generator expressions are often preferred over explicit for loops — they are more concise, more Pythonic, and frequently faster because the iteration happens in optimised C code.

Related terms: Iterator, Comprehension, Range

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.