Comprehensions in Python
Comprehensions in Python provide us with a short and concise way to construct
new sequences (such as lists, set, dictionary etc.) using sequences which have been
already defined. Python supports the following 4 types of comprehensions:
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
List Comprehensions:- List Comprehensions provide an elegant way to create new
lists. The following is the basic structure of a list comprehension:
Syntax:-
output_list = [output_exp for var in input_list if (var satisfies this condition)]
Note that list comprehension may or may not contain an if condition. List
comprehensions can contain multiple for (nested list comprehensions).
Example : Suppose we want to create an output list which contains only the even
numbers which are present in the input list. Let’s see how to do this using for
loops and list comprehension and decide which method suits better.