Introduction:
Python is a popular language that allows programmers to write elegant, easy-to-write and read code like plain English. The unique feature of Python is a different type of comprehensions.
In Python, there are three types of comprehensions viz. List, Dictionary and Set.
By the end of this blog, you’ll understand the full power of Python comprehensions and how to easily use its functionality.
- LIST COMPREHENSION
List: List is a collection of data surrounded by square brackets and each element are separated by a comma.
List Comprehension: Is also surrounded by square brackets but instead of the list of elements inside it contain expression like for loop &-or followed by if-clauses.
Example:
a. Create a List of the square of numbers between 1 to 100.
# Without List comprehension
SquaresWithoutComprehension = []
for i in range(1,101):
SquaresWithoutComprehension.append(i**2)
## List Comprehension
SquaresWithComprehension = [i**2 for i in range(1,101)]
b. List comprehension with the condition.
# Suppose we have List consist movie names with released year.
MoviesYear = [('Star Wars',2019),('Glass',2020),('The Upside',2018), ('The LEGO Movie 2',2020),('Cold Pursuit',2017),
('Hotel Mumbai',2020)]
## Problem: Create List of movies released in 2020?
Movies_20 = [title for (title, year) in MoviesYear if year == 2020]
c. List comprehension – Mathematical Applications.
# Suppose we have List of numbers 1 to 10.
Numbers = [1,2,3,4,5,6,7,8,9,10]
## Problem 1: Perform scalar multiplication i.e multiply each number with 2 and store result into the List.
ScalarMultiplication = [4*X for X in Numbers]
### Problem 2: Perform cartesian multiplication between List A and B.
A = [1,2,3,4]
B = [10,11,12,13]
CartesianProduct = [(a,b) for a in A for b in B]
##Output:
[(1, 10), (1, 11), (1, 12), (1, 13), (2, 10), (2, 11), (2, 12), (2, 13), (3, 10), (3, 11), (3, 12), (3, 13), (4, 10), (4, 11), (4, 12), (4, 13)]
Explanation:
The above will produce the same result but when we use list comprehension the line of codes get reduced and the same operation is done with a single line of code.
- DICTIONARY COMPREHENSION
Dictionary: A dictionary is a collection which is unordered, changeable and indexed. In Python dictionary written with curly brackets, and they have key and value pairs.
DictionaryExample = {"IDE": "JupyterNotebook", "Language": "Python", "Version": 3}
Dictionary Comprehension: A dictionary comprehension is also a collection which is unordered, changeable and indexed, where Key-Value pairs generated with help of expression.
Example of Dictionary Comprehension:
a. Create dictionary where Key as Alphabets and Value as the number of times alphabets occurred in the sentence (Dictionary definition).
# Sentence
DictDefination = "A dictionary is a collection which is unordered, changeable and indexed. In Python written with curly brackets, and they have keys and values."
## Dictionary comprehension
AlphabetDictionary = {
key: DictDefination.count(key) for key in DictDefination
}
b. Dictionary Comprehension – Mathematical Application
# Problem: Create dictionary where Key as number and Value as cube of key i.e. number.
## Dictionary comprehension
NumSquareDictComprehension = {key:key**3 for key in range(1,10)}
OR
NumSquareDictComprehension = {f"The square of {key} is":key**3 for key in range(1,10)}
- SET COMPREHENSION
Set: In Python Set is unique, unordered, mutable collection of elements. Set where elements enclosed with curly brackets and elements separated by a comma.
SetExample = {‘Python’,’Java’,’R’}
Set Comprehension: Simillar to list comprehension but consist of a collection of unique, unordered, mutable elements, where dictionary elements inside it contain an expression.
Example of Set Comprehension:
a. Create Set consist squares of a number between 1 to 10.
SquareSet = {num**2 for num in range (1,11)}
b. Create Set of Unique elements available in the list.
# Suppose list having duplicate elements
CarBrands = ['BMW','Chevrolet','Bentley','BMW']
## Set comprehension only give unique elements from the above List
CarBrandDict = {Brand for Brand in CarBrands}
Advantages of Comprehensions:
- Easy to implement.
- Reduce the number of lines of code.
- Faster execution and utilise fewer resources.
Disadvantages of Comprehensions:
- More number of comprehensions used in the program increase the complexity of code.
- Complicate to understand expression working.
Conclusion:
As discussed above, different types of comprehensions available in Python. Above implemented are basic examples expressions used in comprehensions can be used to call the functions. Most often, list and dictionary comprehension use to simplify the code.
Hope, this blog helps you understand some effective and easy-to-use Python techniques.
Thank you for reading!!






