Combine For Loop & if-else statement in Python

In this Python tutorial, you will learn how to combine a for loop with if / if-else statements in Python.

Table Of Contents

Introduction

As we know that a List Comprehension is used to create a new list based on the condition or an expression.

I have a question?

Have you observed that list comprehension will use expressions by combining for loop with conditional statements like if,if-else, etc.?

Advertisements

Yes. in many cases we can combine for loop with conditional statements.

Now, let’s see how to combine a for loop with conditional statements by considering all conditional scenarios.

Combine a for loop and if statements

In this scenario, we will use for loop with just a single if statement to check a condition.

Syntax:

[iterator for iterator in iterable/range(sequence) if (condition) ]
  1. for-loop takes a list or sequence of elements.
  2. An iterator is used to iterate the elements in for loop.
  3. The conditional statement can be used to combine with for loop and return the iterator based on the condition specified inside it.

Example:

In this example, we are creating a list comprehension to return the iterator only if the below conditions satisfy.

  1. Return only the elements that are divisible by 2, with the condition – if (iterator%2==0)
  2. Return only the elements that are divisible by 5, with the condition – if (iterator%5==0)
  3. Return only the elements that are greater than 4, with the condition – if (iterator>4)
# Create a list comprehension and return only 
# the numbers that are divisible by 2 from the list
# of 10 integers
mylist_comprehension = [iterator 
                        for iterator in [1,2,3,4,5,6,7,8,9,10]
                        if (iterator % 2==0) ]

#return the list
print(mylist_comprehension)

# Create a list comprehension and return only 
# the numbers that are divisible by 5 from the list
# of 10 integers
mylist_comprehension = [iterator
                        for iterator in [1,2,3,4,5,6,7,8,9,10]
                        if (iterator % 5==0) ]

#return the list
print(mylist_comprehension)

# Create a list comprehension and return only 
# the numbers that are divisible by 4 from the list
# of 10 integers
mylist_comprehension = [iterator
                        for iterator in [1,2,3,4,5,6,7,8,9,10]
                        if (iterator > 4) ]

# Print the list
print(mylist_comprehension)

Output:

[2, 4, 6, 8, 10]
[5, 10]
[5, 6, 7, 8, 9, 10]

From the above output, we can see that based on the condition, we are getting elements from the list

Combine for loop and nested-if statements in Python

If you want to combine a for loop with multiple conditions, then you have to use for loop with multiple if statements to check the conditions. If all the conditions are True, then the iterator is returned.

Syntax:

[iterator for iterator in iterable/range(sequence) if (condition1) if (condition2) .........]
  1. A for-loop takes a list or sequence of elements.
  2. An iterator is used to iterate the elements in for loop.
  3. The conditional statements can be used multiple times in combination with a for loop in List comprehension. It returns the iterator based on the conditions specified inside them.

Example:

In this example, we are creating a list comprehension to return the following only if

  1. the elements that are divisible by 2 with the condition – if (iterator%2==0)
  2. the elements that are divisible by 5 with the condition – if (iterator%5==0)
  3. the elements that are greater than 4 with the condition – if (iterator>4)
# Create a list comprehension and return only the numbers
# that are divisible by 2, 5 and 4 from the list of 10 integers
mylist_comprehension = [iterator
                        for iterator in [1,2,3,4,5,6,7,8,9,10]
                        if (iterator%2==0)
                        if (iterator%5==0)
                        if (iterator>4) ]

# Print the list
print(mylist_comprehension)

Output:

[10]

We can see that only 10 satisfies the above three conditions.

Combine for loop and if-else statements

If you want to combine for loop with if-else statements, then you have to specify if-else in front of for loop. If the condition satisfies, then the if block will be executed, otherwise the else block will be executed.

Syntax:

[ statements if (condition) else statements  for iterator in iterable/range(sequence) ]
  1. A for-loop takes a list or sequence of elements.
  2. An iterator is used to iterate the elements in for loop.
  3. If the condition satisfies, then the if block will be executed, otherwise else block will be executed.

Example:

In this example, we are creating a list comprehension and checking the following

  1. Select the elements that are divisible by 2 from the list and replace others by 0.
  2. Select the elements that are divisible by 5 from the list and replace others by 0.
  3. Select the elements that are greater than 4 from the list and replace others by 0.
# Create a list comprehension and look for
# numbers which are divisible by 2
myList = [ num if (num % 2 == 0) else 0
           for num in [1,2,3,4,5,6,7,8,9,10] ]

# Print the list
print(myList)

# Create a list comprehension and look for
# numbers which are divisible by 5
myList = [ num if (num % 5 == 0) else 0
           for num in [1,2,3,4,5,6,7,8,9,10] ]

# Print the list
print(myList)

# Create a list comprehension and look for
# numbers which are divisible by 4
myList = [ num if (num % 4 == 0) else 0
           for num in [1,2,3,4,5,6,7,8,9,10] ]

# Print the list
print(myList)

Output:

[0, 2, 0, 4, 0, 6, 0, 8, 0, 10]
[0, 0, 0, 0, 5, 0, 0, 0, 0, 10]
[0, 0, 0, 4, 0, 0, 0, 8, 0, 0]

In the first example, if the elements are divisible by 2, we are returning the element otherwise we are returning 0.
In the second example, if the elements are divisible by 5, we are returning the element otherwise we are returning 0.
In the third example, if the elements are divisible by 4, we are returning the element otherwise we are returning 0.

How to Combine for loop and nested if-else statements?

In python, to execute multiple conditions, elif is used along with the if and else. But if you want to execute multiple/nested if-else statements then if-else is specified one after another. elif is not used here.

Syntax:

[ statement1 if (condition1) else statement2  if (condition2) else other_statement  for iterator in iterable/range(sequence) ]
  1. A or-loop takes a list or sequence of elements .
  2. An iterator is used to iterate the elements in for loop.
  3. If condition1 is satisfied, then statement1 is executed. Otherwise it goes to second if block and checks for the condition2. If the condition2 is satisfied then the statement2 is executed.
  4. If all conditions are not satisfied, then the other_statement is executed.

Example:

In this example, we will check the elements are divisible by 2 or 5 from the list.

# Create a list and using comprehension look for numbers which
# are divisible by 2 or 5
myList = [ str(num) + ' is Multiple of 2' if num % 2==0 else
           str(num) + ' is Multiple of 5' if num %5==0
           else str(num) + ' is Not a Multiple of 5 & 2'
           for num in [1,2,3,4,5,6,7,8,9,10] ]

# Print the List
print(myList)

Output:

['1 is Not a Multiple of 5 & 2',
 '2 is Multiple of 2',
 '3 is Not a Multiple of 5 & 2',
 '4 is Multiple of 2',
 '5 is Multiple of 5',
 '6 is Multiple of 2',
 '7 is Not a Multiple of 5 & 2',
 '8 is Multiple of 2',
 '9 is Not a Multiple of 5 & 2',
 '10 is Multiple of 2']

Output Analysis

  • For the elements which are divisible by 2, we are displaying ‘N is Multiple of 2’.
  • For the elements which are divisible by 5, we are displaying ‘N is Multiple of 5’.
  • For the elements which not are divisible by 2 or 5, we are displaying ‘N is not a Multiple of 5 & 2’.

Summary

We have seen four scenarios to combine the for loop with conditional statements. Based on your application, you can use and implement it in your project. Happy Learning.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top