List/Dictionary Comprehension is an elegant one-liner to iterate over a List/Dictionary. They allow us to create new objects based on the already existing ones.
The syntax for both List and Dictionary Comprehension are pretty similar and although I'll be discussing both, I'll use List comprehension to talk about nest comprehension and conditional comprehension.
The 'Normal' way of iterating over a list using For Loops
Let's assume we have a list of numbers and we want to create a new list that stores the squares of the numbers. This is how we would do it using for loops
List Comprehension
Using List Comprehension we could write lines 2-4 in a single line.
As you can see, it looks much cleaner and elegant.
Dictionary Comprehension
Let's assume we want to create a dictionary that stores the index as a key and the value at that index as the value.
List Comprehension with an If Condition
Let's say we want to store the square of the number only if it's an even number. We can simply add an if statement after the iterable
List Comprehension with If/Else Condition.
Now, suppose we want to store the squares of even numbers and the cubes of odd numbers.
The syntax is slightly different as compared to list comprehension with if statement.
Nested List Comprehension
We can have an outer for loop with an inner for loop.
The first for loop would be the outer for loop and the second for loop would be inner for loop. The expression (i,j) would evaluate (0,0) , (0,1) , (0,2).... since j is in the inner for loop.
Some tips
- Don't overuse List/Dictionary Comprehension. It is a one-liner for a reason. Although it makes your code look clean, ensure it is readable and can be understood by other developers
- List comprehension doesn't call append during every iteration and in general, they are faster than for loops. However, if you are using a complex function inside your list comprehension, it will affect performance.