List comprehensions in python

What are list comprehensions in python?
List comprehensions provides us a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable  or to create a subsequence of those elements that satisfy a certain condition.
Syntax: -A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
#Print list of event numbers less than 10
evens = []
for i in range(10):
     if i % 2 == 0:
         evens.append(i)
print(evens)
#Output:-
[0, 2, 4, 6, 8]

#Print same list using list comprehension
[i for i in range(10) if i % 2 == 0]
#Output
[0, 2, 4, 6, 8]

Example explanation:-In the above example we first used a normal for loop to create a list of even numbers less than 10. In the first line, we initialized an empty ‘evens’ list. Then we used range operation in for loop which will make the for loop run from 0 to 10. In the next statement, we check if the number is divisible by 2 and if yes then we append the value to evens list.
In the case of a list comprehension, we achieved the same task using a single line where we used square brackets to let python understand that the code is a list comprehension. Within the square bracket, we first used ‘i’ operator followed by for-in loop with range 0 to 10. It is followed by the if condition to extract only even numbers from the for loop. Advantages of list comprehensions:-Traditional for loop may work, but it actually makes things slower for Python because the interpreter works on each loop to determine what part of the sequence has to be changed. A list comprehension is more efficient, it is also shorter and involves fewer elements. Hope you found this short post useful.