Scripting >> Python >> Examples >> Advanced >> How to use List Comprehension including nested lists

 

Objective Sample Code
Given integers X, Y, Z, to print a list of possible coordinates (x,y,z) on a 3D grid where the sum of x+y+z is not equal to N
where 0 <= x <= X
where 0 <= y <= Y
where 0 <= z <= Z
# List comprehension syntax [ expression for item in list if conditional ]
X = int(raw_input())
Y = int(raw_input())
Z = int(raw_input())
N = int(raw_input())

L = []
[L.append([x,y,z]) for x in range(X+1) for y in range(Y+1) for z in range(Z+1) if ((x+y+z) != N )  ]
print L 
Create a list of even numbers for a given range >>> x = [i for i in range(10) if (i % 2 == 0)]
>>> print x
[0, 2, 4, 6, 8]
Create a list of squares given a range of integers
>>> squares = [x**2 for x in range(10)]
>>> print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Identify the numbers in a string >>> string = "Hello 12345 World"
>>> numbers = [x for x in string if x.isdigit()]
>>> print numbers
['1', '2', '3', '4', '5']