val
is the variable that takes the value of the element inside the sequence on each iteration.range()
function. range(10)
will generate numbers from 0 to 9 (10 numbers).range(start, stop, step_size)
. step_size defaults to 1 if not provided.range
object is "lazy" in a sense because it doesn't generate every number that it "contains" when we create it. However, it is not an iterator since it supports in
, len
and __getitem__
operations.list()
.range()
function in for
loops to iterate through a sequence of numbers. It can be combined with the len()
function to iterate through a sequence using indexing. Here is an example.for
loop can have an optional else
block as well. The else
part is executed if the items in the sequence used in for loop exhausts.break
keyword can be used to stop a for loop. In such cases, the else part is ignored.else
and prints No items left.for...else
statement can be used with the break
keyword to run the else
block only when the break
keyword was not executed. Let's take an example: