Search⌘ K
AI Features

The for Loop

Explore how to use Python for loops to iterate through sequences such as numbers, lists, and strings. Understand the structure of a for loop, how to utilize the range function to control iterations, and ways to process data items one by one. This lesson helps you write repetitive code clearly and effectively by mastering looping techniques and applying them to practical examples.

A for loop uses an iterator to traverse a sequence, such as a range of numbers, the elements of a list, or the characters in a string. In simple terms, the iterator is a variable that goes through the list. The iterator starts at the beginning of the sequence and ends when it reaches the end.

Structure

In a for loop, we need to define three main things:

  1. The name of the iterator

  2. The sequence to be traversed

  3. The set of operations to perform

The loop always begins with the for keyword. The body of the loop is indented to the right:

The in keyword specifies that the iterator will go through the values in the sequence/data structure. Notice the colon at the end of the for statement.

Forgetting to put the colon at the end is a common mistake that beginners make. Be mindful of that.

Looping through a range

In Python, the built-in range() function can be used to create a sequence of integers. This sequence can be iterated over through a loop. A range is specified in the following ...

Python 3.8
range(start, end, step)
...