Amit Upadhyay
2 min readMay 13, 2020

--

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:

1-> List Comprehensions
2-> Dictionary Comprehensions
3-> Set Comprehensions
4-> Generator Comprehensions

1-> List Comprehensions:
output_list = [output_exp for var in input_list if (var satisfies this condition)]

my_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]

evn_numbers = [n for n in my_list if n%2 == 0] # Accept only even number from my_list.
print(evn_numbers)
print([i*2 for i in range(1,10)]) # print twice of the number in range between 1 to 10

2-> Dictionary Comprehensions:
Extending the idea of list comprehensions, we can also create a dictionary using dictionary comprehensions.
The basic structure of a dictionary comprehension looks like below.
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

print({j:j*3 for j in range(1,10)}) # Print i as key and value as i * 3
print({j:j*3 for j in range(1,10) if type(j) == int}) # Print i as key and value as i * 3

3-> Set Comprehensions:
Set comprehensions are pretty similar to list comprehensions. The only difference between them is that set comprehensions use curly brackets { }.

print({num for num in my_list}) # Create set for my_list

4-> 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.

print(*(num+num for num in my_list if num <7)) ### print number + number, use * or use for loop to iterate.

Output are below for all the print →

--

--