How to do List Comprehension using if else in Python

List comprehensions are a powerful feature in Python that allows you to construct lists or sequences of values in a concise and readable way. They become even more versatile when you incorporate if-else conditions into them. In this comprehensive guide, we will dive deep into the world of list comprehensions with if-else statements, exploring their syntax, applications, and various methods to make your code more efficient and expressive.

Understanding List Comprehension Syntax

List comprehensions in Python follow a specific syntax pattern. They begin with an expression enclosed in square brackets, followed by a for clause. Additional clauses or if-else clauses can follow. The focus here is on if-else clauses within list comprehensions, which provide conditional control.

List comprehensions consist of three main components:

  1. Expression: The expression to be evaluated for each item in the iterable.
  2. Iterable: The sequence of items to iterate over.
  3. Conditional: An optional condition that filters the items to be included in the resulting list.

1) List Comprehension with If-Else

When dealing with if-else conditions in list comprehensions, the syntax becomes slightly more complex:

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

Here’s a breakdown of the components:

  1. expression1: The expression to be evaluated if the condition (conditional1) is True.
  2. conditional1: The condition that determines whether to use expression1 or expression2.
  3. expression2: The expression to be evaluated if the condition (conditional1) is False.
  4. item: The current item being processed in the iterable.

Let’s create a list of patterns using if-else conditions:

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

In this example, we generate a pattern where even indices in the list receive '*', and odd indices receive '+'.

2) List Comprehension with Only If Clause

If you only need to filter items based on a condition without an else clause, the syntax simplifies:

[item for item in iterable if conditional]

Let’s create a list of multiples of 5 using only the if clause:

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

In this example, we filter the numbers that are multiples of 5 from the range.

3) List Comprehension with Nested If Statements

List comprehensions can also handle multiple if conditions. For instance, we can create a list of even numbers that are multiples of 4:

a = [k for k in range(30) if k % 2 == 0 if k % 4 == 0]
print(a)
OUTPUT:
[0, 12, 24]

This example demonstrates filtering based on multiple conditions, only including numbers that are both even and multiples of 4.

4) 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: 
 ['*', '*', '**', '***', '****', '*****']

5) 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: 
 *****

6) list comprehension using if statement in Python

The syntax of using if statement using list comprehension

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]

7) 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]

8) 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:

  1. List comprehensions
  2. 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]

9) List Comprehensions with 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.

10) 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)
['+', '-', '+', '+', '+', '+', '-', '+', '+', '+', '-', '+', '+', '+', '-']

11) Comparison case of list comprehension using if else

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

List comprehensions in Python provide a concise and efficient way to create lists with conditional logic. In this comprehensive guide, you’ve learned how to use if-else conditions, nested if statements, and filter items based on various conditions. Remember that the for...in structure should always come at the end of the list comprehension syntax when handling if-else conditional clauses.

To further enhance your Python programming skills, consider exploring additional Python programming tutorials. Happy coding!

Leave a Comment

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