Like any other programming language, looping in Python is a great way to avoid writing repetitive code. However, unlike Python's while loop, the for loop is a definitive control flow statement that gives you more authority over each item in a series.

Whether you're a Python beginner or you already have some experience with it, having a solid grasp of its for loop is the key to solving array-related problems. Here, we take a look at how Python's for loop works and some examples of how you can use it to solve coding challenges.

How For Loops Work in Python

Python's for loop works by iterating through the sequence of an array. In essence, its useful when dealing with sequences like strings, lists, tuples, dictionaries, or sets. An in keyword usually follows a for loop in Python.

A for loop has similar characteristics in all programming languages. For instance, while there are syntax differences, the characteristic of Java's for loop is similar to how Python's for loop works.

The general syntax of a Python for loop looks like this:

        for new_variable in parent_variable:
execute some statements

As stated earlier, unlike a while loop, the for loop is more powerful as it offers more control in a flow.

To have a better understanding, a for loop typically looks like this example statement: "for every male student you meet in a class, write down one, else, write down it's a class of females only."

That statement is a simple instruction that tells you to keep writing one for every male student you encounter in a particular class. It's a continuous loop. However, to initiate the for loop in that instance, you must encounter a male student. If not, then you write down the else statement.

If the above statement doesn't have an else condition, then you wouldn't write anything. That means it's an empty array.

How to Use Python's For Loop: Practical Examples

Now let's take a look at some practical examples of how to use a for loop in Python.

The code snippet below outputs each of the items in a list:

        items = ["shoe", "bag", "shirts", "lamp"]
for i in items:
print(i)

You can also modify the code above to output any item that has the letter "a":

        items = ["shoe", "bag", "shirts", "lamp"]
for i in items:
if "a" in i:
print(i)

A for loop in Python also takes a direct else statement:

        b=[2, 3, 5, 6]
for i in b:
print(i)
else:
print("Loop has ended")

You can use a break statement to alter the flow of a for loop as well:

        b=[2, 3, 5, 6]
for i in b:
if i>3:
break
print(i)

You can also use the continue keyword with a for loop:

        b=[2, 3, 5, 6]
for i in b:
if i>3:
continue
print(i)

Using a for Loop With List and String Literals in Python

Now take a look at the code below to output all positive integers between 1 and 100. To do this, you first create a list of numbers between 1 and 100 using Python's built-in range function:

        for x in range(1, 101):
print(x)

You can modify that block of code by introducing a conditional statement to output all odd numbers between 1 and 100 as well:

        for x in range(1, 101):
if x%2==1:
print(x)

However, you can also create a "2 by output" multiplication table of the output of the code above. To achieve this, you only need to add a few more statement like this:

        for x in range(1, 101):
if x%2==1:
print(x, "x", 2, "=", x * 2)

Now that you've seen how a for loop works with a list of integers. Let's have a look at how we can use a for loop with strings.

The code below returns a sequence of each string in a sentence:

        a = "How to use a for loop in Python"
for i in a:
print(i)

We can also count the number of strings (including spaces) in the variable a using a for loop:

        a = ["How to use a for loop in Python"]
for i in a:
print(i.count(''))

Output: 32

However, you can also place a for loop in a separate variable and get a similar result by rewriting the code above like this:

        a=["How to use a for loop in Python"]
c=[b.count('') for b in a]
print(c)

Output: [32]

Note: To get the character count, ensure that there is no space between the quotation marks in the parenthesis that follows the count keyword.

You can also modify each of the last two code snippets above to create a simple word counter using a for loop. All you need to do in this case is insert a single space between each quotation mark in the parenthesis:

        a=["How to use a for loop in Python"]
for i in a:
  print(i.count(' ') + 1)

Output: 8

Like you did for the character count, you can also rewrite the the word count code above by placing the for loop in a variable like this:

        a = ["How to use a for loop in Python"]
c=[b.count(' ') + 1 for b in a]
print(c)

Output: [8]

Pay close attention to the single space that's now between the quotes in parenthesis.

Related: How to Create and Re-Use Your Own Module in Python

Using a Python For Loop With an Array

You can also use a for loop to get a particular element from an array.

Assume that you have an array of sheep with values of "Yes" for "healthy" animals and "No" for "unhealthy" sheep. Each sheep then has a unique name, and you want to quarantine all the sick ones.

You can use a for loop to output all unhealthy sheep. To see how useful a for loop is in that case, the code below outputs the name of all unhealthy sheep from the array:

        array = [{"name":"Sheep1", "healthy":"Yes"},
 {"name":"Sheep3", "healthy":"No"},
 {"name":"Sheep4", "healthy":"Yes"},
 {"name":"Sheep5", "healthy":"Yes"},
 {"name":"Sheep8", "healthy":"No"},
 {"name":"Sheep7", "healthy":"No"},
 {"name":"Sheep9", "healthy":"No"}
 ]

for sheeps in array:
   if sheeps["healthy"]=="No":
   print("Quarantine", sheeps["name"])

Using Nested For Loop in Python

A nested for loop is useful when you want to output each element in a complex or nested array. It works by placing a loop inside another loop. The example code below outputs each of the items in the nested list. However, it outputs only the keys of the dictionary:

        nested_list = [[1, 2, 4, 5], {"name":"Python", "method":"write"}]

for dict in nested_list:
  for i in dict:
  print(i)

A better understanding of Python's list and arrays is useful when dealing with a nested for loop.

For Loops or While Loops, Which is Better?

Depending on the problem at hand, each of for and while loops has its use case in Python. Although a for loop is more common, that doesn't make mastering the while loop less important.

While a for loop offers more general solutions across programming languages, placing it above the while loop is erroneous. It's always better to consider either of them for solving specific problems, rather than believing that one is more useful than the other. Besides, as a Python programmer, you can't do without either of them.