Python for Loops for Iteration Over a Sequence
Python's for loop is a control flow statement that allows for definite iteration based on a sequence. The for loop structure is relatively straightforward: we define a new variable in memory, which will be assigned each value in the given sequence during iteration, and then repeatedly execute a portion of code exactly once for each element in our sequence. As with most Python code that contains a nested block, the for loop ends in a colon, and the block of code to be repeated is indented one level.
# Python for loop: # we define a new variable, "value", # and reference a sequence, "sequence" for value in sequence: # do something repeatedly print(value) # here, we will print each value # in the sequence on a new line
Python for loops can be executed using any Python type that is iterable, including lists, dictionaries, strings, tuples, or sets. Technically, any Python object can have the iteration protocol implemented, including user-defined types, but these are the most commonly used built-in types. Python also has a number of generators built into the language, such as range(), which can be used to create an iterable without needing to define a list or other data structure.