List Comprehension and Dictionary Comprehension in Python
In today’s article, we are going to discuss a very important topic, that is, Python comprehension. It is a very powerful way to perform complex operations and manipulate iterables.
List Comprehension:
First, we discussed lists and after that, we see some examples of lists comprehensions
What are lists?
Lists are mutable(changeable) data types. They can be of any type like strings, numbers, sets, Booleans, etc. They are created by using square brackets.
List1=[1, 2, 4.5, ‘ram’, ‘neha’, True]
We can access them with indexes starting from zero. It also supports slicing.
Suppose you want to iterate over a list and append the result to a new list.
But with Python list comprehension, we can do this in one line.
List Comprehension with Conditions:
List comprehensions also provide a way to check for conditions and filter out the elements you don’t need from the list.
Even and Odd numbers with list comprehension:
Power of number with List Comprehension:
If-else Condition in List Comprehension
we use the if-else statement in the first position and we incremented one to even numbers and squared the odd numbers.
List Comprehension with Nested Conditions:
we use nested if statement in first check number is devisable by 2 and after that, we check with 5
Python Dictionary Comprehension:
Lets us now see how dictionary comprehensions work.
Dictionary :
Dictionaries are data types in Python that allows us to store data in key/value pair. For example:
>>> x = { “name”: “Vishal”, “age”:25, “email”: “oldmonk007@gmail.com”}
we look at some numbers square in the dictionary
we solve the same problem with the help of dictionary comprehension
The output of both programs will be the same.
Let’s compare this syntax with dictionary comprehension from the above example.
now we see another example of the dictionary comprehension
Conditionals in Dictionary Comprehension:
we have data of cricketers we find even runs with help of comprehensions
if-else Conditional Dictionary Comprehension:
we have some data name and age in the dictionary we use if else statement to find old and young
Another example of dictionary comprehension:
I am glad you liked the article. Share with your friends.