✌Various Comprehensions in Python🤗
Comprehensions
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.
Need For Comprehensions
Comprehension is an elegant way to define and create data based on existing values. Comprehension is generally more compact and faster than normal functions and loops for creating list or tuple or dictionary. However, we should avoid writing very long comprehensions in one line to ensure that code is user-friendly.
TYPES OF Comprehensions
Comprehensions in Python:
The comprehension consists of a single expression followed by at least one for
clause and zero or more for
or if
clauses.
There are three comprehensions in Python.

List Comprehensions:
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a sub sequence of those elements that satisfy a certain condition.
Syntax:
[expression for item in iterable if conditional]
The expression can be any arbitary expression, complex expressions, tuple, nested functions, or another list comprehension.
This is equivalent to
for item in iterable:
if conditional:
expression
Return Type:
List
Using List Comprehension:
A list comprehension consists of brackets[]
containing an expression followed by a for
clause, then zero or more for
or if
clauses. The result will be a new list resulting from evaluating the expression in the context of the for
and if
clauses that follow it.

1. List comprehension vs for loop.
By using List Comprehension, it is more concise and readable comparing to for loop.
Finding square of numbers using List Comprehension vs for loop:
#Using List Comprehension
l2=[i*i for i in range(1,11)]
print (l2)
#Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # Using for loop l1=[] for i in range(1,11): a=i*i l1.append(a) print (l1)
#Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2. List comprehension vs filter.
filter:
Returns an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator
Finding Even Numbers Using List Comprehension vs filter():
#Using filter function
evennumber=filter(lambda x: x%2==0,range(1,11))
#filter() returns an iterator.
print (evennumber) #Output:<filter object at 0x0144EC10>
print (list(evennumber))#Output:[2, 4, 6, 8, 10]
#Using List Comprehension
evenno=[n for n in range(1,11) if n%2==0]
print (evenno) #Output:[2, 4, 6, 8, 10]
3.List Comprehension vs map.
map:
Return an iterator that applies a function to every item of iterable, yielding the results.
Finding square of numbers using List Comprehension vs map():
#Using map() function
l1=map(lambda x:x*x,range(1,11))
#Returns an iterator(map object)
print (l1)
#Output:<map object at 0x00C0EC10>
print (list(l1))
#Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#Using List Comprehension
l2=[x*x for x in range(1,11)]
print (l2)
#Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4. Nested loops in List Comprehension.
List comprehension can contain one or more for clause.
Example 1: Flatten a list using List Comprehension with two ‘for’ clause:
l1=[[1,2,3],[4,5,6],[7,8,9]]
l2=[num2 for num1 in l1 for num2 in num1]
print (l2)
#Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]
5.Multiple if condition in List Comprehension.
List comprehension can contain zero or more if clause.
Example: Finding numbers that are divisible by 2 and 3.
l1=[1,2,3,4,5,6,7,8,9,10,11,12] l2=[n for n in l1 if n%2==0 if n%3==0] print (l2)
#Output:[6, 12]
6. The expression can be tuple in List Comprehension.
We can mention expression as a tuple in a list comprehension. It should be written within parentheses. Otherwise, it will raise Error. The result will be a list of tuples.
Example 1: Creating a list of tuples using List Comprehension with two ‘for’ clause:
a1=['red','green','blue'] b1=[0,1,2] a2=[(a,b) for a in a1 for b in b1] print (a2)
#Output:[('red', 0), ('red', 1), ('red', 2), ('green', 0), ('green', 1), ('green', 2), ('blue', 0), ('blue', 1), ('blue', 2)]
If the expression is a tuple and if not enclosed within parentheses, it will raise Syntax Error.
a1=['red','green','blue'] b1=[0,1,2] a2=[a,b for a in a1 for b in b1] #SyntaxError: invalid syntax
Example 2:Using zip() function in List Comprehension:
l1=['red','green','blue'] l2=[0,1,2] l3=[(n1,n2) for n1,n2 in zip(l1,l2)] print (l3)
#Output:[('red', 0), ('green', 1), ('blue', 2)]
zip() in python
7. List comprehension can be used to call a method on each element.
Example 1: Calling strip() method on each element in the list. It is used to strip the white spaces.
l1=[" a","b "," c "] l2=[i.strip() for i in l1] print (l2)
#Output:['a', 'b', 'c']
Example 2: Calling the upper() method on each element in the list.
l1=['red','blue'] l2=[i.upper() for i in l1] print (l2)
#Output:['RED', 'BLUE']
8. List comprehension can contain complex expressions and nested functions.
Example 1:In the below example, in expression we are using the strip method and int function.
l1=[' 1',' 2'] l2=[int(i.strip()) for i in l1] print (l2)
#Output:[1,2]
Example 2: In the below example, in expression, we are using abs() and str() function.
l=[-2,-1,0,3,4] l3=[str(abs(i)) for i in l] print (l3)
#Output:['2', '1', '0', '3', '4']
9. Nested List Comprehension.
The expression in a list comprehension can include another list comprehension also.
Example: First List comprehension given as expression will return a list of even numbers from 0 to 10. Nested list comprehension will return that expression (list of even numbers from 0 to 10) three times(range(3)).
l1=[[n for n in range(10) if n %2==0] for n1 in range(3)]
print (l1)
#Output:[[0, 2, 4, 6, 8], [0, 2, 4, 6, 8], [0, 2, 4, 6, 8]]
Set Comprehensions:
Like List comprehension, Python supports Set Comprehension also.Set comprehension is written within curly braces{}
.Returns new set based on existing iterables.Return Type:Set
Syntax:{expression for item in iterable if conditional}How to find even numbers using set Comprehension:s1={n for n in range(1,11) if n%2==0}print (s1)
#Output:{2, 4, 6, 8, 10}
How to find the square of numbers using Set Comprehension.s1={n*n for n in range(1,11)}
#Sets are unordered.
print (s1)
#Output: {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}
If condition in Set comprehension:Below example, we are calculating the square of even numbers.
The expression can be a tuple, written within parentheses.
We are using if condition to filter the even numbers.
Sets are unordered. So elements are returned in any order.s={(n,n*n) for n in range(1,11) if n%2==0}
#Sets are unordered print (s)
#Output:{(6, 36), (4, 16), (10, 100), (2, 4), (8, 64)} print (type(s))
#Output:<class 'set'>
Dictionary Comprehensions:
Like List and Set comprehension, Python supports Dictionary Comprehension.A dict comprehension, in contrast, to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.
Dictionary comprehension is written within curly braces
{}
.In Expression key and value are separated by:
Syntax
{key:value for (key,value) in iterable if conditional}
Return Type:
dict
How to find the square of numbers using Dictionary Comprehension.
d1={n:n*n for n in range(1,11)}
print (d1)
#Output:{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
How to iterate through two dictionaries using dictionary comprehension:d1={'color','shape','fruit'} d2={'red','circle','apple'} d3={k:v for (k,v) in zip(d1,d2)} print (d3) #Output: {'fruit': 'circle', 'shape': 'red', 'color': 'apple'}
If Condition in Dictionary Comprehension:
Zero or more if clause can be used in dictionary comprehension.
In the below example, we are calculating the square of even numbers.d={n:n*n for n in range(1,11) if n%2==0} print (d)#Output:{2: 4, 4: 16, 6: 36, 8: 64, 10: 100} print (type(d))#Output:<class 'dict'>
Finding the number of occurrences using dictionary comprehension:
In the below example, we are calculating the number of occurrences of each character in a string. We can call the method
count()
on each element in the string.count()
will return the number of occurrences of a substring in the string.We are calculating the number of occurrences of each word in the list by calling
count()
on each word in the list.
#finding the number of occurrences of each character in the string s="dictionary" d={n:s.count(n) for n in s} print (d)
#Output:{'d': 1, 'i': 2, 'c': 1, 't': 1, 'o': 1, 'n': 1, 'a': 1, 'r': 1, 'y': 1} #finding the number of occurrences of each word in list using dict comprehension l=["red","green","blue","red"] d={n:l.count(n) for n in l} print (d)#Output:{'red': 2, 'green': 1, 'blue': 1}
Comments
Post a Comment