Python comprehensions are a concise way to create lists, dictionaries, and sets. They allow for a more readable and often faster approach to generating these collections.
List Comprehension:
It is just a shorter way of writing the same code (syntax) enhancing its readability and optimality.
Let us understand it with an example:
numbers=[1,2,3,4,5,6,]
squares=[]
for number in numbers:
squares.append(number**2)
print(squares)
Output:
[1, 4, 9, 16, 25, 36]
With list comprehension we can rewrite it as
numbers=[1,2,3,4,5,6,]
squares=[number ** 2 for number in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25, 36]
So the syntax is as follows: [ expression for iteration ]
where the comprehension starts with square bracket followed by expression we want to return over the loop iterating over a sequence. Thus it ultimately produces a list by evaluating the expression for each item in iterable.
Let us look at one more example:
List Comprehension with Conditional expression:
input=[1,2,3,4,4,5,6,7,7]
output = []
for var in input_list:
if var % 2 == 0:
output.append(var)
print("Output List using for loop:", output)
Output:
Output List using for loop: [2, 4, 4, 6]
With list comprehension we rewrite it as follows:
input=[1,2,3,4,4,5,6,7,7]
output=[ var for var in input if var%2==0 ]
print(output)
Output:
[2,4,4,6]
Here in the list comprehension post the for loop the if used is basically as a filter . What would happen if the “if ” clause is followed by “else” here.
output=[ var for var in input if var%2==0 else “Sorry”] . It will raise an error as here the if in our comprehension is being used as filter and we can’t have an else as filter because we are not making new value we are just iterating over a sequence and allowing certain values based on that condition i.e filter either lets thing or not based on a condition so no need of an else clause here.
Dictionary Comprehension:
Similar to list comprehension , they provide a compact way to create dictionaries.
Syntax : { key: value for item in iterable if condition } elaborating it as:
{key:value for (key, value) in iterable if (key, value satisfy this condition)}
Example:
Let us start with a simple example:
squares = {}
for key in range(1,6):
squares[key]= key**2
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
It can be rewritten as:
squares = {x: x**2 for x in range(1, 6)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Let us look at another example using loop and conditional expression:
input =[1, 2, 3, 4, 5, 6, 7]
output={}
for x in input:
if x % 2 ==0:
output[x]= x**2
print("Output Dictionary using loop :", output)
Output :
Output Dictionary using loop : {2: 4, 4: 16, 6: 36}
With dictionary comprehension it can be rewritten as:
input =[1, 2, 3, 4, 5, 6, 7]
output={x:x**2 for x in input if x % 2==0}
print("Output Dictionary using loop :", output)
Output:
Output Dictionary using loop : {2: 4, 4: 16, 6: 36}
Set Comprehension :
Set comprehensions in Python provide a concise way to create sets. They are similar to list comprehensions but use curly braces {}
instead of square brackets []
.
Syntax: {expression for item in iterable if condition}
Let us look at an example:
list1=[1,2,3,4,5,6]
input=set()
for x in list1:
input.add(x*2)
print(input)
It can be rewritten using set comprehension as :
list1=[1,2,3,4,5,6]
input={x*2 for x in list1}
print(input)
Output:
{2, 4, 6, 8, 10, 12}
Let us loop at one more example with loop and conditional expression:
list1=[1,2,3,4,5,6]
input=set()
for x in list1:
if x%2==0:
input.add(x*2)
print(input)
Output:
{8, 4, 12}
It can be rewritten as:
list1=[1,2,3,4,5,6]
input={x*2 for x in list1 if x%2==0}
print(input)
Output:
{8, 4, 12}
Hence similar output.