Enduring Effectiveness of List Comprehension in Python
List comprehension is a neat and aesthetic way to combine lists with for loop. For Example, you want to double items of a list -
x = [1, 2, 3]
y = [ ]
for item in x:
y.append(item*2)
List comprehension version -
y = [item*2 for item in x]
Result: y = [2, 4, 6]
Notice that there is not much change in syntax except the expression (i.e. item*2) moving at the start and complete doing away of .append method. You can go for more complex list comprehension following the same path.
Nested loop with list comprehension and if condition -
x = [1, 2, 3]
y = ['Red', 'Blue', 'Green']
z = []
z = [item*color for color in y for item in x if len(color)>3]
Result: z = ['Blue', 'BlueBlue', 'BlueBlueBlue', 'Green', 'GreenGreen', 'GreenGreenGreen']
#Python
#AIML
#datascience