Skip to main content

Discrete Math with SageMath: Learn math with open-source software

Section 1.5 Iteration

Iteration is a programming technique that allows us to efficiently write code by repeating instructions with minimal syntax. The for loop assigns a value from a sequence to the loop variable and executes the loop body once for each value.
Here is an example of list comprehension, a concise way to create lists. Unlike Python’s range(), the Sage range syntax for list comprehension includes the ending value.
We can also specify a condition in list comprehension. Let’s create a list that only contains even numbers.