Python For Loops
What is a For Loop?
A for loop is used to iterate through an iterable. An iterable is something you can go one by one through, which can be a list, a tuple, a string, or a set. To iterate through an iterable means to go one by one through it. Then, inside of our for loop, we can do something whenever we iterate through one element in the iterable.
Below is the general form of a for loop:
for [element] in [iterable]:
# do something
The range
function
The range
function is a built-in Python function which returns integers from a start number to an end number, where the start and end numbers are included. Below is the syntax:
range(start, end)
The range
function is useful for doing something a certain amount of times.
If you put just one number in the range
function, the range
function will default to:
range(0, number - 1)
It goes from zero to the number minus one so it's easier to go through a list.
However, do note that the range
function doesn't return a list. It actually returns an object of the range
class. In order to convert it into a list, we can run the list
function/class on it, like this:
print(list(range(5))) # output is [1, 2, 3, 4]
Learn more about this in our Casting tutorial!