Python Comprehensions
Python Comprehensions
Topperworld.in
Comprehensions
❖ List Comprehensions
List Comprehensions provide an elegant way to create new lists. The
following is the basic structure of list comprehension:
Syntax:
output_list = [output_exp for var in input_list if
(var satisfies this condition)]
Example:
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
©Topperworld
Python Programming
Output:
❖ Dictionary Comprehensions
Extending the idea of list comprehensions, we can also create a dictionary
using dictionary comprehensions.
Syntax:
output_dict = {key:value for (key, value)
in iterable if (key, value satisfy this
condition)}
Example:
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {}
Output:
©Topperworld
Python Programming
❖ Set Comprehensions
Set comprehensions are pretty similar to list comprehensions. The only
difference between them is that set comprehensions use curly brackets { }
Example:
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
Output:
❖ 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.
©Topperworld
Python Programming
Example:
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
Output:
©Topperworld