List comprehension in python
List Comprehension is a one line method. It is used to reduce the lines of code. The syntax is easy to understand. It will give the output as list. In this List comprehension we can use n number of for loop. It is faster than for loop.
For loop
It is used to reduce the lines of code. Instead of creating a separate "for" loop iteration and performing append operation in the list, we can use List comprehention. The output will be stored in the list.
Syntax:
Variable_name = [expression for item in iterable]
n = [ 1, 2, 3, 4, 5] l = [ x*2 for x in n ] print(l)
Output
[2, 4, 6, 8, 10]
If statement
It is used to reduce the lines of code. Instead of creating a separate "for" loop iteration in the list and to perform "if" operation, we can use List comprehention. The output will be stored in the list.
Syntax:
Variable_name = [ expression for item in iterable if condition == True]
n = [ 1, 2, 3, 4, 5] l = [ x for x in n if x % 2 == 0 ] print(l)
Output
[2, 4]
If else statement
It is used to reduce the lines of code. Instead of creating a separate "for" loop iteration in the list and to perform "if else" operation, we can use List comprehention. The output will be stored in the list.
Syntax:
Variable_name = [ expression if condition == True else expression for item in iterable ]
n = [ 1, 2, 3, 4, 5] l = [ "EVEN" if x % 2 == 0 else "ODD" for x in n] print(l)
Output
['ODD', 'EVEN', 'ODD', 'EVEN', 'ODD']
Else if statement
It is used to reduce the lines of code. Instead of creating a separate "for" loop iteration in the list and to perform "if else" operation, we can use List comprehention. The output will be stored in the list.
Syntax:
Variable_name = [ expression1 if condition1 else expression2 if condition2 else expression3 for item in iterable ]
n = [ -1, 2, 0, 3, -4] l = ["Positive" if x > 0 else "Zero" if x == 0 else "Negative" for x in n] print(l)
Output
['Negative', 'Positive', 'Zero', 'Positive', 'Negative']
Nested for loop
It is used to reduce the lines of code. Instead of creating a separate "nested for" loop iteration in the list, we can use List comprehention. The output will be stored in the list.
Syntax:
Variable_name = [ expression for item1 in iterable1 for item2 in iterable2 if condition == True]
n = [ 1, 2] m = [ 3, 4] l = [( x, y) for x in n for y in m if x != y] print(l)
Output
[(1, 3), (1, 4), (2, 3), (2, 4)]