Python List Comprehension is the idea that is not common in most of the language. It is basically used to generate a list of elements having some specific property. Moreover, Python List Comprehension make code smaller but effective.
The basic structure consist of Python List Comprehension three parameters.
- Expression for output
- A variable representing member of input sequence
- Predicate (Optional)
Conditionals in Python List Comprehension:- It is possible to add a condition to it and it’ll add only those items to the list that meet the condition (for which the condition is True).
This code will give output
Nested Conditionals in Python List Comprehension :- With a Python list comprehension, it doesn’t have to be a single condition; you can nest conditions. Here’s an example.
x = [i for i in range(8) if i%2==0 if i%3==0]
Output:- [0, 6]
Python Dictionary Comprehension:-
Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed.The way to do dictionary comprehension in Python is to be able to access the key objects and the value objects of a dictionary.
We can also make changes to the key values.
For example :-
Note:-Dictionary comprehension is a powerful concept and can be used to substitute for loops and lambda functions. However, not all for loop can be written as a dictionary comprehension but all dictionary comprehension can be written with a for loop.