if statement comprehension python code example

Example 1: list comprehension python if else

[statement if condition else statement for _ in iterable_object]
#statement are without assignment

Example 2: python list comprehension if else

# if/else
[f(x) if condition(x) else '' for x in sequence]

Example 3: list comprehension if

[f(x) for x in sequence if condition]

Example 4: python if else list comprehension

# Basic syntax for if:
desired_elements = [f(x) for x in iterable_object if condition]

# Basic syntax for if else:
desired_elements = [f(x) if condition else g(x) for x in iterable_object]

# Basic syntax for if elif else:
desired_elements = [f(x) if condition elif condition_2 g(x) else h(x) for x in iterable_object]

# Example usage:
# Say you want to return the square of elements if elements are less 
# than 10, otherwise you just want to return the elements themselves:
your_list = [1, 7, 13, 11, 23, 2, 17, 42, 8, 5]
new_list = [x**2 if x < 10 else x for x in your_list]
print(new_list)
--> [1, 49, 13, 11, 23, 4, 17, 42, 64, 25]

Example 5: python list comprehension if else

>>> original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16]
>>> prices = [i if i > 0 else 0 for i in original_prices]
>>> prices
[1.25, 0, 10.22, 3.78, 0, 1.16]

Example 6: list comprehension for loop and if

matrix = [[1, 2], [3,4], [5,6], [7,8]]
transpose = [[row[i] for row in matrix] for i in range(2)]
print (transpose)