Python For Loops

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-oriented programming languages.

Looping through a List

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Looping through a String

for x in "banana":
  print(x)

The range() Function

To loop through a set of code a specified number of times, we can use the range() function.

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Using the range() function

for x in range(6):
  print(x)

Note that range(6) is not the values from 0 to 6, but the values 0 to 5.

To define a custom start parameter, add a parameter: range(2, 6), which means values from 2 to 5. To define the step value (how much it increments), add a third parameter: range(2, 30, 3).


Exercise

?

What will the function range(3) produce when iterated in a for loop?