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.
Learn how to use for loops, one of the most useful skills to master in beginner programming.
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)