List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.
The basic syntax is
[ expression for item in list if conditional ]
This is equivalent to:
for item in list:
if conditional:
expression
Example
1)
2)
The basic syntax is
[ expression for item in list if conditional ]
This is equivalent to:
for item in list:
if conditional:
expression
Example
1)
x = 1
y = 1
z = 1
lis = []
lis = [ [i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k) != N]
print lis
Above is the nested for loop
y = 1
z = 1
lis = []
lis = [ [i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k) != N]
print lis
Output
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
Above is the nested for loop
x = [i for i in range(10)]
print x
This will give the output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print x
This will give the output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]