Course Outline (Part 17)

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-orientated programming languages.


1. for loop with sequence

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

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

The for loop does not require an indexing variable to set beforehand.

Looping Through a String

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

for x in "banana":
    print(x)

2. for loop with range()

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.

for x in range(6):
    print(x) # Prints 0 to 5

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

You can also specify the start value and the increment value (step):

for x in range(2, 10, 2):
    print(x) # Prints 2, 4, 6, 8

3. break and continue in for

Just like with while loops, you can use break and continue.

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and moves to the next one.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    if x == "banana":
        break
    print(x) # Prints only "apple"

4. else in for loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished.

for x in range(6):
    print(x)
else:
    print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by a break statement.


5. Nested for loops

A nested loop is a loop inside a loop. The “inner loop” will be executed one time for each iteration of the “outer loop”.

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
    for y in fruits:
        print(x, y)

Output:

red apple
red banana
red cherry
big apple
...

6. pass statement

for loops cannot be empty. If you have a for loop with no content, put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:
    pass

Discussion

Loading comments...