What is the need for an if statement inside for loop in Python and how to use it? We can iterate blocks of code using for
loop and using an if
statement along with it we can check for a specific condition and perform until the condition is False
. For loop iterates over a sequence(such as a list, or tuple) and execute a specific action for each item in the sequence. In this article, I will explain the concept of an if statement within for loop with examples.
Below are some use cases of using if Statement with for Loop:
- if statement is used to check the condition of the iteration item.
- break statement is used mostly with if statement to break the loop.
- continue statement is used to skip the current iteration and go to the next one.
1. Quick Examples of For Loop with If Statement
If you are in a hurry, below are some quick examples of using Python for loop with If statement.
# Quick examples of for loop with if statement
# Example 1: Iterate list using for loop with if
courses = ["c", "c++", "python", "java", "pandas"]
courses1 = ["java","python","pandas","sparks"]
for i in courses:
if i in courses1:
# Example 2: Iterate given lists
# Using for loop with if else statement
courses = ["c", "c++", "python", "java", "pandas"]
courses1 = ["java","python","pandas","sparks"]
for i in courses:
if i in courses1:
print(i)
else:
print(i)
# Example 3: Skip the loop
# Using if and continue statement
courses=["java","python","pandas","sparks"]
for x in courses:
if x == 'pandas':
continue
print(x)
# Example 4: Exit the loop
# Using if and break statement
courses=["java","python","pandas","sparks"]
for x in courses:
print(x)
if x == 'pandas':
break
# Example 5: Using break statement inside
# The nested loop with if
courses1=["java","python"]
courses2=["pandas","java","python"]
for x in courses1:
for y in courses2:
if x==y:
break
print(x ,y)
2. Python For Loop with If Statement
Using for
loop with an if statement in Python, we can iterate over a sequence and perform different tasks for each item in a sequence until the condition falls a False. Let’s take two sets of lists and perform them using for
loop with an if statement.
In the below example, the loop iterates through each element (i
) in the courses
list. The if
statement checks whether the current i
is present in the courses1
list. If it is, the print(i)
statement is executed, and the common elements between the two lists are printed. The common elements, in this case, are “python”, “java”, and “pandas”.
# Iterate given lists using for loop with if
courses = ["c", "c++", "python", "java", "pandas"]
courses1 = ["java","python","pandas","sparks"]
for i in courses:
if i in courses1:
print(i)
Yields below output.
From the above, using for
loop we have iterated each item in a given list named courses
. For every iteration, it will check if the item of courses
presents in another list named courses1
. If the item presents both two lists then will print the item as a output.
3. For Loop with If Statement and Else statement
Let’s take another example using for
loop with if
statement and else
statement. Here, For every iteration, it will check if the item of i==java
then the loop will be terminated and else block won’t execute.
If the i!=java
then the if condition will not be executed and our program will not reach the break statement to terminate the loop. Only then the else block will execute.
# Iterate given lists
# Using for loop with if else statement
courses = ["c", "c++", "python", "java", "pandas"]
for i in courses:
if i =="java":
print("Java is found")
break
else:
print("Java is not found")
Yields below output.
4. Using For Loop with If Statement and Continue
Below are some more examples we are going to see on a for loop with a break, continue, and if statements.
Using the if
statement along with the continue
statement we can skip the current iteration of the loop within a specific condition and continue
to the next iteration of the loop.
# Skip the loop using if and continue statement
courses=["java","python","pandas","sparks"]
for x in courses:
if x == 'pandas':
continue
print(x)
Yields below output.
# Output:
java
python
sparks
Here, I have taken courses
as a list, which is iterated using for
loop with the continue
statement. Here as you can see continue
statement is used within the if
condition. If the loop reaches the 'pandas'
the condition in the if
the statement becomes True, so the continue
statement will execute and skips the current iteration(pandas) and go for the next iteration.
Note: continue
statement doesn’t exit the for/while loop.
5. Using For Loop with If Statement and Break
Sometimes you would like to exit from the python for
/while
loop when you meet certain conditions, using if
and break statement you can exit the loop when the condition meets. The example is given below.
# Exit the loop using if and break statement
courses=["java","python","pandas","sparks"]
for x in courses:
print(x)
if x == 'pandas':
break
Yields below output.
# Output:
java
python
pandas
From the above example, I have taken the courses
variable as a list that is iterated using for
loop. We have applied a break
statement based on x=='pandas'
condition. If the iteration reaches the pandas
value, the for loop will exit using a break
statement.
The above example exits loop when x
value equals to pandas
.
6. Nested for Loop with If Statement
If a loop presents inside the body of another loop is called a nested loop
. The inner loop will be executed n number of times for each iteration of the outer loop within a specific condition using if
statement. The example is given below.
If the break
statement is inside a nested loop, the break
statement will end the innermost loop and the outer loop continue executing. Let’s take an example for a better understanding.
# Using break statement inside the nested loop with if
courses1=["java","python"]
courses2=["pandas","java","python"]
for x in courses1:
for y in courses2:
if x==y:
break
print(x ,y)
In the above example, the inner loop will be executed three times(‘pandas’, ‘java’, ‘python’) for each iteration of the outer loop.
Possibilities of the outer loop for the first iteration:
java, pandas
java, java
in this case, the condition satisfies so the innermost loop ends. Then the control goes to the outer loop.
Possibilities of the outer loop for the second iteration :
python, pandas
python, java
python, python
in this case, the condition satisfies so the innermost loop ends.
Yields below output.
# Output:
java pandas
python pandas
python java
Frequently Asked Questions on Python For Loop with If Statement
The combination of a for
loop and an if
statement in Python is used to iterate over elements in a sequence (such as a list, tuple, or string) and perform conditional actions based on certain criteria. This allows you to execute different blocks of code for different elements in the sequence.
Common use cases include filtering elements in a sequence based on certain conditions, performing specific actions for elements meeting certain criteria, or transforming elements based on specified rules.
You can nest a for loop inside another for loop, an if statement inside another if statement, or a combination of both. This allows for more complex control flow and logic in your code.
It’s good practice to use meaningful variable names, write clear and concise conditions, and add comments to explain the purpose of the loop and conditions. Additionally, consider using list comprehensions if you are creating a new list based on a condition.
Use a for
loop with an if
statement to find and print only the even numbers from a list of integers.For example, the for
loop iterates over each number in the numbers
list. The if
statement checks whether the current number is even (number % 2 == 0
). If the condition is true, it prints a message indicating that the number is even.
Conclusion
In this article, I have explained the concept of an if statement within a for loop in Python and used these combinations while iterating how we can control and perform the given sequence with examples. Also learned the significance of the if statement to break & continue the looping.
Related Articles
- Python For Loop with If Statement
- Python For Loop Break Statement
- How to terminate a script in Python?
- Iterate Over an Array in Python
- For Loop Continue And Break in Python
- How to Increment for Loop in Python
- For Loop Enumerate in Python
- Get Counter Values in a for Loop in Python?
- Access Index in for Loop in Python
- For Loop Break Statement in Python
- How to Perform Decrement for Loop in Python
- How to Write Python For Loop in One Line?
- Python if __name__ == “__main__”: Explain?
- Python Nested if else Statement Examples