Python Tutorial Part 9 | Conditional Flow: For Loops

Learn how to use ‘for loops’ in Python to create complex, iterable tasks such as modifying lists, combining lists into dictionaries, or iterating over a dictionary.

This article explores a commonly used looping mechanism in Python: the ‘for loop.’ This allows for repeated tasks using a specific iteration sequence. You will also learn how a for loop differs from a while loop.

For Loop: General Structure

The for loop in Python is the more widely used looping construct as opposed to the while loop. Its general structure follows below:

The keyword “for” instantiates the for loop. The value is an item in the sequence, where the sequence is an “iterable.” An iterable is an item that can be iterated or “stepped through.” Although iterables may sound confusing, you have already been working with them since the start of this tutorial. Some of the data types and structures we learned earlier, such as the list, dictionary, and string, are all iterable objects. We will take a look at an example shortly. Lastly, the tabbed or nested action is any code (single or multiline) that we wish to perform on each value of the iterable sequence.

Let’s go back to our familiar example of the jet fuel mercaptan oxidation treatment used in learning lists. Recall the general process flow diagram below:

Process visual for python project

Figure 1. The chemical process flow used to relate concepts of a Python list. 

Recall our previous list denoting the index or order of processing equipment in this chemical process flow:

For each chemical processing equipment object in this process, let’s print out the equipment names, one step at a time, in ascending order of the process:

The output appears below:

caustic prewash merox reactor caustic settler water wash salt bed clay bed Process finished with exit code 0

Each equipment value was printed per iteration of the loop and ultimately terminated at the end of the sequence. This is a key difference between a while loop and a for loop. While loops run until the initial test condition becomes false, whereas a for loop will automatically terminate at the end of an iterable.

Accessing the Index

The value of a for loop within an iterable has an index number associated with it. We could create a manual counter variable, but Python already has an automated index value available through the enumerate() function. To make the prior example more clear, let’s print each revolution or iteration of the loop by displaying the index:

The output appears below:

Loop iteration number: 0, value: caustic prewash Loop iteration number: 1, value: merox reactor Loop iteration number: 2, value: caustic settler Loop iteration number: 3, value: water wash Loop iteration number: 4, value: salt bed Loop iteration number: 5, value: clay bed Process finished with exit code 0

Conditional Statements in a For Loop

Conditional statements can be used within the action code block of a for loop. Let’s create a second list of prices that are related to the jet_fuel_mercaptan_oxidation_treatment list of equipment:

The output appears below:

price: $1150.0 is less than $2000.00 price: $15000.34 is greater than $10000.00 $5500.56 price: $1500.45 is less than $2000.00 $4000.24 $7000.96 Process finished with exit code 0

Zip Parallel Traversal

Working with individual lists is great for learning the basic concepts. However, in reality, some tricky situations arise where you may need to traverse two lists in parallel. Much like current flow through multiple resistors in a parallel circuit, the for loop can flow through two lists simultaneously.

Parallel resistor network

Figure 2. Simple parallel circuit. 

For example, we have the prices and equipment of the “Jet Fuel Mercaptan Oxidation Treating” process contained in separate lists. In order to traverse both the equipment and the associated prices at the same time we can use the zip() function. The zip() function pairs iterables from the two lists in an output tuple. Breaking this down into smaller steps, the relation of list objects appears below:

The output appears below:

[(‘caustic prewash’, 1150.0), (‘merox reactor’, 15000.34), (‘caustic settler’, 5500.56), (‘water wash’, 1500.45), (‘salt bed’, 4000.24), (‘clay bed’, 7000.96)] Process finished with exit code 0

Used within a loop, the relation of pricing to equipment using the zip() function becomes:

The output appears below:

Equipment Name: caustic prewash, Capital Cost: $1150.0 Equipment Name: merox reactor, Capital Cost: $15000.34 Equipment Name: caustic settler, Capital Cost: $5500.56 Equipment Name: water wash, Capital Cost: $1500.45 Equipment Name: salt bed, Capital Cost: $4000.24 Equipment Name: clay bed, Capital Cost: $7000.96 Process finished with exit code 0

List Comprehensions

List comprehensions are a fast and efficient way of creating a new list based on an existing list. For example, let’s say the equipment prices were quoted in 2019 and they don’t factor in the massive inflation run-up over the last five years. To create an inflation-adjusted price list, we could use a list comprehension:

The output appears below:

[1495.0, 19500.44, 7150.73, 1950.59, 5200.31, 9101.25] Process finished with exit code 0

Iterating over a Dictionary

This article has heavily covered list iteration using a for loop, but what about the key and value pairs of a dictionary? Dictionaries are also iterable in Python. We will model the Jet Fuel Mercaptan Oxidation Treating process as a dictionary below:

The dictionary can be accessed based on tuple pairs of key/value pairs, individual keys, or individual values using the following methods.

.items()

This method returns a tuple of the key and associated value:

The output appears below:

equipment_1 caustic prewash equipment_2 merox reactor equipment_3 caustic settler equipment_4 water wash equipment_5 salt bed equipment_6 clay bed Process finished with exit code 0

.keys()

This method only returns the keys of the dictionary:

The output appears below:

equipment_1 equipment_2 equipment_3 equipment_4 equipment_5 equipment_6 Process finished with exit code 0

.values()

This method only returns the values of the dictionary:

The output appears below:

caustic prewash merox reactor caustic settler water wash salt bed clay bed Process finished with exit code 0

Wrapping Up

For loops are a powerful iteration tool in Python. While this article is not all-encompassing, I hope it has shared some of the more useful tools used in looping with for loops.


Copyright Statement: The content of this website is intended for personal learning purposes only. If it infringes upon your copyright, please contact us for removal. Email: admin@eleok.com

Leave a Comment