How to do list comprehension using if else in Python

List comprehensions are one of the most useful tools in Python. They allow you to construct a sequence of values, or a list, which contains data. Moreover, Python has a powerful feature that is a list comprehension, which makes it easy to write code in a concise way. However, if the provided data contain some conditional data, then results are accomplished by using conditional statements. In this article, we’ll take a look at the syntax of list comprehensions based on if-else conditions. So, Let’s dive into the article!

How to use List Comprehension using if-else conditions?

However, list comprehension makes it easier to perform if-else conditions within a one-liner command line. The syntax of List Comprehension is:

An expression is surrounded by brackets, followed by a for clause, followed by zero or more for clauses or if clauses or if-else clauses.

Comprehensive note to use the List comprehension using if else

The following example illustrates how if-else conditionals can be controlled inside a list comprehension.

However, it is difficult to remember the order, that expression1 has to be before if and expression2 has to be after else

So to remember the list comprehension using if-else condition syntax order by taking the example from daily life. 

LIST COMPREHENSION IF-ELSE Syntax

[expression1(item) if conditional1 else expression2(item) for item in iterable] 

Remember the list comprehension if-else syntax by the following example:

"The boy doesn’t go for play Hockey if it rains, else they will definitely play"
Boys will go outside if if it is sunny day else boys will not go outside to play  for hockey in hockey_ground

For example:

pattern = ["*" if i%2==0 else "+" for i in range(6)]
print('pattern: \n', pattern)
pattern: 
 ['*', '+', '*', '+', '*', '+']

LIST COMPREHENSION only if clause Syntax

However, if the list comprehension contains only if clause, then the syntax will be 

The syntax for using only if-clause:

[item for item in iterable if conditional] 

Boys will go outside to play for hockey in hockey_ground if it is sunny day

For instance:

a = ([k for k in range(11) if (k%5==0)])
print('table of 5: \n', a)
table of 5: 
 [0, 5, 10]

Keep in mind that the, For…in structure should be used at the end of the syntax structure if handling the list comprehension using if-else conditions.

How to make a list from items in an if-else condition using List comprehension?

List comprehension uses the following syntax to use items in an if else conditions using list comprehension. 

[expression1(item) for item in iterable] 
[item for item in iterable if conditional] 
[expression1(item) if conditional1 else expression2(item) for item in iterable] [expression1(item) if conditional1 else expression2(item) if conditional2 else expression3(item) for item in iterable]

Any conditional clause doesn’t need to include an item’s value. 

If you want to make a list that uses the stripe() function to remove empty string/whitespace in the list ‘a’, you can do the following:

a= '12 3456 7  89'
List = [k for k in a if k.strip()]
List
['1', '2', '3', '4', '5', '6', '7', '8', '9']

Following are some methods to convert the conditional data in a more concise and readable way using List comprehension in Python.

List comprehension using if-else with join() function

List comprehension using if-else condition in aggregation with join() and range() functions.  

#using list comprehension with join() function
#this will print the pattern upto 5 counts
ifelse=(['*'*i if i else '*' for i in range(6)])
print('pattern: \n',ifelse)
#bound the list to print all pattern 
pattern: 
 ['*', '*', '**', '***', '****', '*****']

Print the pattern at that iterator at index 5

#using list comprehension with join() function
#this will print the pattern upto 5 counts
ifelse=(['*'*i if i else '*' for i in range(6)])
print('pattern: \n',ifelse[5])
#bound the list to print pattern which iterate over the index 5
pattern: 
 *****

list comprehension using if statement in Python

The syntax of using if statement using list comprehension

[item for item in iterable if condition]

a = ([k for k in range(21) if (k%2==0)])
print('table of 2: \n', a)
table of 2: 
 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Performing the above operation without if-else conditions using list comprehension.

[j*k for k in range(0,11) for j in range(2,3)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

list comprehension using nested if statements in Python.

Condition: only even numbers that are multiples of 4 will be added to the list ‘a’.

List= [item for item in iterable if condition == True] 

#using muliple if
a = [k for k in range(30) if k%2==0 if k%3==0 if k%4==0]
print(a)
[0, 12, 24]

list comprehension with if else in Python.

[expression if condition1 else condition2 for item in iterable]

pattern = ["*" if i%2==0 else "+" for i in range(6)]
print('pattern: \n', pattern)
pattern: 
 ['*', '+', '*', '+', '*', '+']

In a list comprehension, there are two things to consider when using if/else statements:

  • List comprehensions
  • Conditional Operators

In the Following Example, there will be no additions or updates to the list except for even numbers.

new_list = [expression for item in iterable if condition == True] 
if_ = [k for k in range(0, 41) if k % 4 == 0]
if_
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40]

List Comprehensions with Conditionals

List Comprehensions with Multiple if Conditionals

Condition: even numbers will be added as ‘+’, the number 5 will be added as ‘***’ and the odd will be added as ‘-’.

a = ['+' if k % 2 == 0 else '***' if k == 5 else '-' for k in range(0, 15)]
a
#print '+' for even, and '-' for old, and for number 5 it print pattern
['+', '-', '+', '-', '+', '***', '+', '-', '+', '-', '+', '-', '+', '-', '+']

Among other things, this example checks to see if the number n is even (that is, if n is divisible by 2 without remainder). New lists include the string “+” if it is true; otherwise, it includes “-“, and at number n=5, it returns a pattern.

List Comprehensions with if-else Conditionals

In the following example, a list comprehension search and match the results with if-else clauses. However, if the number n is even (that is, if k is divisible by 2 without remainder), then New lists include the string “+” if the number is even; else wise, it updates the list with the string “-” for the odd number.

List=[0, 3, 4, 8, 12, 16, 19, 20, 24, 28, 31, 32, 36, 40, 41]
plus_min = ["+" if k % 2 == 0 else "-" for k in List]
print(plus_min)
['+', '-', '+', '+', '+', '+', '-', '+', '+', '+', '-', '+', '+', '+', '-']

Comparison case of list comprehension using if else

Case:1

a= (", ".join(["*" if k else "**" for k in range(3)]))
print(a, type(a))
**, *, * <class 'str'>

Case:2

a= ["*" if k else "**" for k in range(3)]
print(a, type(a))
['**', '*', '*'] <class 'list'>

In Case:1 and Case:2, When 0 is generated by the function range(), if k generates False (execute else statement and print (**)). Otherwise, it yields to True and print ‘*’. However, join() function returns the list comprehension in String data-type. And in Case:2, the returns list.  

Conclusion

This tutorial covers list comprehension using if-else. It covers the different ways to use list comprehension using if, list comprehension using if-else clause, and ways to accomplish this task. However, remember that the for..in structure should come at the end of the list comprehension syntax when handling the if-else conditional clause. 

If you want to learn more about Python Programming, visit Python Programming Tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *