List Comprehension
List comprehension is a shorthand method to create a new list by changing the elements of the already available iterable (like list, set, tuple, etc).
Syntax:
new_list = [expression for variable in iterable]
Traditional way
Python3
# code new_list = [] for variable in iterable: new_list.append(expression) |
How does it work?
We iterate over all the values in the iterable one by one and keep storing them in a variable. Now, based on the value of the variable, the expression is evaluated for each value and this expression is stored in the new_list created.
Let’s have a look at an example:
Traditional way
Python3
nums = [ 1 , 2 , 3 , 4 , 5 ] squares = [] for val in nums: squares.append(val * val) print (squares) |
One Liner
Python3
nums = [ 1 , 2 , 3 , 4 , 5 ] squares = [val * val for val in nums] print (squares) #Output [1, 4, 9, 16, 25] |
List comprehension with conditionals
We can also use conditionals in list comprehension. For example, if we need to create a list containing only even numbers from a given list:
Traditional way
Python3
nums = [ 1 , 2 , 3 , 4 , 5 ] even_nums = [] for val in nums: if val % 2 = = 0 : even_nums.append(val) print (even_nums) |
One liner
Python3
nums = [ 1 , 2 , 3 , 4 , 5 ] even_nums = [val for val in nums if val % 2 = = 0 ] print (even_nums) #Output [2, 4] |
List comprehension and nested loops
If we are given two lists one containing the x coordinates and the other containing the y coordinates and we have to create a list containing unordered pairs from these:
Traditional way
Python3
x = [ 1 , 2 , 3 ] y = [ 4 , 5 , 6 ] coordinates = [] for xcor in x: for ycor in y: coordinates.append((xcor, ycor)) print (coordinates) |
One liner
Python3
x = [ 1 , 2 , 3 ] y = [ 4 , 5 , 6 ] coordinates = [(xcor, ycor) for xcor in x for ycor in y] print (coordinates) #Output [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)] |
Similarly, we can also perform comprehensions in sets, dictionaries, etc
10 Useful Python One Liners That Developers Must Know
Python is known for its easy-to-code and intuitive syntax. And one-liners are like the cherry on the cake which makes Python a more beautiful and beloved programming language. There are numerous features in Python Language and one of its most loved features is its one-liners. Writing Code in Python is already easy compared to other programming languages and using the one-liners makes it more easier and cool. Now let’s see what are these Python one-liners.