/  Technology   /  if/else in a list comprehension

if/else in a list comprehension

if/else in a list comprehension


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]

The if-else clause:

Syntax: [variable if expression else expression for variable sequence]

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