The nested comprehensions introduction.
Welcome back! Now that we know how to create a regular list comprehension, we can start working on more complex forms of them. We will start by using nested For loops. If you would like to see the previous blogs that go over the structure of list comprehensions, click here.
Nested For loops
To start, nested For loops are very useful if you want to iterate through matrices. You can also use it if you have to iterate through lists within lists. In this example, we’ll iterate through a matrix to flatten it.
nums = [[1,2,3],[4,5,6],[7,8,9],]nums = [i for l in nums for i in l]print(nums)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In this case, how we would read this is: “Give me the item for each list in num for each item in that list” The first loop iterates through the lists in the list and, the second loop iterates through the items of the list that the first For loop provides.
Nested If Statements
When it comes to If statements it may get a bit complex. The process is still simple and in the end, it depends on what application you are looking for. To start let’s look at what it would look like if we work with nested If statements before the For loop.
When we use nested If statements before the For loop we have to use the following syntax:
[ output if condition 1 else output (for if 2) if condition 2 else output]
When we use it in the beginning we need to maintain an Else statement, unlike when it’s used at the end. The Else statement in a nested If works to concatenate the second If to the comprehension, the last Else statement is what we want the output to be if the previous conditions aren’t met.
Let’s try an example. In this example we want it to iterate through a list and return if a number is odd, even, or a letter.
nums = [1,2,"a",3,"r",4,"b",5,6,"w",7,8,9,"f",10]nums= ["Letter" if type(i) == str else "Even" if i%2 == 0 else "Odd" for i in nums]print(nums)
['Odd', 'Even', 'Letter', 'Odd', 'Letter', 'Even', 'Letter', 'Odd', 'Even', 'Letter', 'Odd', 'Even', 'Odd', 'Letter', 'Even']
In this case, we would read this as: “Return “Letter” if the item’s type is a string else return “Even” if the item’s floor division is 0 else return “Odd” for every item in nums”.
When the If statement is after the For loop, we don’t need to provide an Else statement. When we use the nested If statement after the For loop, it is not as versatile as the first example. Python treats the nested for loops as And condition but we can use Or as well if we need a different output.
When we use nested If statements after the For loop we have to use the following syntax:
[ expression for element in list if condition 1 if condition 2 ]
Let’s try an example. In this example we want it to iterate through a list and return if a number is even and divisible by 5. We’ll also use it with the Or statement to see the different outputs.
#Return a list of numbers that are even and floor division by 5 is 0nums = [1,2,3,4,5,6,7,8,9,10]nums= [i for i in nums if i%2 ==0 if i%5==0]print(nums)
#Return a list of numbers that are even or floor division by 5 is 0nums = [1,2,3,4,5,6,7,8,9,10]nums= [i for i in nums if i%2 ==0 or i%5==0]print(nums)
[2, 4, 5, 6, 8, 10]
We will read the previous comprehensions as follows:
- Return each item in nums if its floor division by 2 is 0 and its floor division by 5 is 0. Returning 10 since it’s the only number that meets those conditions.
- Return each item in nums if its floor division by 2 is 0 or its floor division by 5 is 0. Returning 2, 4, 5, 6, 8, and 10 since they meet those conditions.
Now finally let’s put it all together and do a more complex example. This exercise was taken from Hacker Rank and you’re able to find it here. The exercise goes as follows:
You are given three integers and representing the dimensions of a cuboid along with an integer . Print a list of all possible coordinates given by (i , j, k) on a 3D grid where the sum of i + j + k is not equal to n. Here, 0≤ i≤x, 0 ≤ j≤y; 0≤k≤z.
#Knowing what we know lets put it all together.x = 1
y = 1
z = 1
n = 2print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ])[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
Let’s give this list comprehension one last read! Return us a list of a, b, and c for each item in the range of 0 to x+1, each item in the range of 0 to y+1, and each item in the range of 0 to z+1 if the sum of a, b, and c is not the same of n.
There we go! That’s your introduction to list comprehensions and their more complicated forms. You can expand on this and make them even more elaborate depending on your needs.