Skip to content

Python iteration methods

In Python, iteration is primarily handled through loop constructs that allow for traversing collections of data, such as lists and dictionaries.^[400-devops-09-scripting-language-python-introduction-readme.md]

Loops

There are two primary primitive loop structures used for iteration in Python.

While loop

A while loop executes a block of code as long as a specified condition remains true.^[400-devops-09-scripting-language-python-introduction-readme.md] This method relies on a counter or index variable that must be manually updated within the loop to eventually terminate the condition.^[400-devops-09-scripting-language-python-introduction-readme.md]

i = 0
while i < 7:
  print(customers[i])
  i += 1

For loop

The for loop is generally used for iterating over sequences, such as lists or dictionaries.^[400-devops-09-scripting-language-python-introduction-readme.md] When iterating over a dictionary, the loop variable corresponds to the dictionary's keys.^[400-devops-09-scripting-language-python-introduction-readme.md]

for customerID in customers:
  print(customers[customerID])

Sources

^[400-devops-09-scripting-language-python-introduction-readme.md]