List comprehension in Python refers to the shortcut and concise way to create a list using for loop or creating a Python list in Pythonic way.
If you want to create a list l1 in Python having some items in it you can create like.
l1= [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Another way to create this list is
l1=[]
for i in range(1, 11):
l1.append(i**2)
You can also create the same list using list comprehension.
Which is
l1=[i**2 for i in range(1,11)]
Creating a list using above technique is called list comprehension.
Creating another list using l2-
l2=[k+2 for i in l1]
then l2 would be
[3, 6, 11, 18, 27, 38, 51, 66, 83, 102]
The basic syntax for list comprehension is
l=[expression for i in sequence]
where expression may be
i
i+2
i**2
i-2
or any expression involving i, if you do not include i then expression will generate a the same element.
Including Decision Making-
You can write expression using decision making statements-
l3= [ n+2 if n < 5 else n**2 for n in range(1,11)]
The output would be
[3, 4, 5, 6, 25, 36, 49, 64, 81, 100]