/  Technology   /  if-else clause in a list comprehension in python
if-else clause in a list comprehension in python

if-else clause in a list comprehension in python

List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. List comprehension in Python is also bounded within square brackets, but instead of the list of data inside it, we enter an expression followed by for loops and if-else clauses.

Syntax:

list_variable = [expression for iterator in sequence]

The above syntax, if you can relate, closely resembles the set-builder notation in mathematics.

Set builder form:

S = {x² : x in {0 ... 5}}

List Comprehension:

S = [x**2 for x in range(6)]

If we only want to extract expression output for a specific set of data from the entire collection of elements, we can use an if clause after the for loop. The expression will be added to the list only if the if clause is ‘True’. Even more than one if clause is allowed, and only if the if clauses return True, do the expressions stay in the list.

Syntax:

[expression for x in sequence if condition]

Example:

LIST = [1,2,3,4,5,6,7,8,9,10]
list = [x for x in LIST if x % 2 == 0]
print(list)

output:

 

The if-else clause:

Syntax:

[variable if expression else expression for variable sequence]

Example:

LIST = [1,2,3,4,5,6,7,8,9,10]
list = ["EVEN" if i % 2 == 0 else i for i in range(10)]
print(list)

output:

The usage of if-else clauses work the same as the ternary operator ?: 

 

Note: We must use both if and else keywords otherwise a SyntaxError is thrown. We can’t use elif here.

 

Leave a comment