Comprehensions provide us with a short and concise way to construct new sequences using sequences which have been already defined. Common applications are to make new sequences 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.Python supports the following comprehensions:
- List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
- Generator Comprehensions
List Comprehensions
List comprehension is used to create new list from an existing list. It consists of an expression followed by for
statement inside square brackets. A list comprehension can optionally contain more for or if statements.
my_list = [2 ** x for x in range(10)] my_list = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
Dictionary Comprehensions
Extending the idea of list comprehensions, we can also create a dictionary using dictionary comprehensions.
input_list = [1,2,3,4,5,6,7] my_dict = {var:var ** 3 for var in input_list if var % 2 != 0} state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur'] my_dict = {key:value for (key, value) in zip(state, capital)}
Set Comprehensions
Set comprehensions are pretty similar to list comprehensions. The only difference between them is that set comprehensions use curly brackets { }.
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] my_set = {var for var in input_list if var % 2 == 0}
Generator Comprehensions
Generator Comprehensions are very similar to list comprehensions. One difference between them is that generator comprehensions use circular brackets whereas list comprehensions use square brackets. The major difference between them is that generators don’t allocate memory for the whole list. Instead, they generate each value one by one which is why they are memory efficient.
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] my_gen = (var for var in input_list if var % 2 == 0) for var in my_gen: print(var, end = ' ')